<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0">

<channel>
	<title>Better-Coding</title>
	<atom:link href="https://better-coding.com/feed/" rel="self" type="application/rss+xml"/>
	<link>https://better-coding.com</link>
	<description>Let's discover IT world together!</description>
	<lastBuildDate>Sun, 26 Feb 2023 17:35:24 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://better-coding.com/wp-content/uploads/2022/01/bc-icon-2-64x64.png</url>
	<title>Better-Coding</title>
	<link>https://better-coding.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Unity3D: Build Flexible detector script using UnityEvent system</title>
		<link>https://better-coding.com/unity3d-build-flexible-detector-script-using-unityevent-system/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Mon, 17 Oct 2022 20:24:39 +0000</pubDate>
				<category><![CDATA[Unity3D]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[unity]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=640</guid>

					<description><![CDATA[Let's build a very useful and flexible detector script, that you can easily use to detect if some body enters the specific space. Then using UnityEvnts system you will be able to flexibly notify other GameObject about this fact. The created detector allows you to use it in various situations in the future without writing any line of code.]]></description>
										<content:encoded><![CDATA[
<p>Let&#8217;s build a very useful and flexible detector script, that you can easily use to detect if some body enters the specific space. Then using UnityEvnts system you will be able to flexibly notify other GameObject about this fact. The created detector allows you to use it in various situations in the future without writing any line of code.</p>



<h2 class="wp-block-heading">Resources</h2>



<p>The final project you can find <a href="https://gitlab.com/better-coding.com/public/unity-3d/unity-3d-sandbox/-/tree/main/FlexibleDetector">on my GitLab</a>. If you prefer video tutorial text, you can watch it on <a rel="noreferrer noopener" href="https://youtu.be/5CqtMUZ8-I4" target="_blank">my YouTube channel.</a></p>



<h2 class="wp-block-heading">Detector script</h2>



<p>Let&#8217;s have a look on the following detector script. The script is a typical MonoBehaviour script and it requires Collider component be able to detect if any other object interacts with the collider. In that case that the script detects any interaction it broadcasts particular events trough UnityEvents system. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="Detector.cs" data-enlighter-group="g1">using UnityEngine;
using UnityEngine.Events;

namespace Commons
{
    [RequireComponent(typeof(Collider))]
    public class Detector : MonoBehaviour
    {
        public UnityEvent&lt;Collider> onTriggerEnter;
        public UnityEvent&lt;Collider> onTriggerStay;
        public UnityEvent&lt;Collider> onTriggerExit;

        private void OnTriggerEnter(Collider other)
        {
            onTriggerEnter?.Invoke(other);
        }

        private void OnTriggerStay(Collider other)
        {
            onTriggerStay?.Invoke(other);
        }

        private void OnTriggerExit(Collider other)
        {
            onTriggerExit?.Invoke(other);
        }
    }
}</pre>



<h2 class="wp-block-heading">Receiver script</h2>



<p>Now it&#8217;s time to implement a MonoBehavior with ability to handle the events emitted by Detector. The only requirement is that the receiver MonoBehaviour has to have implemented a public method with the same parameters as emitted events have.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="DummyReceiver.cs" data-enlighter-group="g2">using UnityEngine;

namespace Commons
{
    public class DummyReceiver : MonoBehaviour
    {
        public void ListenOnTriggerEnter(Collider other)
        {
            Debug.Log("ListenOnTriggerEnter");
        }

        public void ListenOnTriggerStay(Collider other)
        {
            Debug.Log("ListenOnTriggerStay");
        }

        public void ListenOnTriggerExit(Collider other)
        {
            Debug.Log("ListenOnTriggerEnter");
        }
    }
}</pre>



<h2 class="wp-block-heading">Putting it together &#8211; UnityEvent system</h2>



<p>It&#8217;s time to put everything together. Create a sphere and add Rigidbody component to it. Then create two empty game objects &#8211; one for Detector and one for Receiver. Add some collider (for example BoxCollider) and the cerated Detector script to the Detector GameObject. Please consider to set <strong>IsTrigger=ture</strong>  flag of the crated collider.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_1-1024x665.jpg" alt="" class="wp-image-715"/></figure>



<p>Then add DummyReceiver script to the Receiver GameObejct. It allows you to handle events generated by Detector.</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_2-1024x665.jpg" alt="" class="wp-image-703" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_2-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_2-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_2-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_2.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>And now the most interesting part, which is event listeners configuration using UnityEvent system. It&#8217;s sounds complicated but it&#8217;s actually very simple. Just select Detector GameObject and add event listeners by clicking &#8220;+&#8221; icon. Drag DummyReceiver GameObejct into the property inspector field (<strong>1)</strong> and choose DummyReceiver&#8217;s event handlers as it is shown below (<strong>2,3,4)</strong>. </p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_3-1024x665.jpg" alt="" class="wp-image-707" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_3-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_3-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_3-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_detector_3.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>If you have done everything correctly the created detector should work. Run the simulation and test the behaviour of the detector by moving the Sphere in and out of the detector&#8217;s collider.</p>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SpringBoot: Resetting H2 database before each integration test</title>
		<link>https://better-coding.com/springboot-resetting-h2-database-before-each-integration-test/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Sun, 16 Oct 2022 22:42:37 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Testing]]></category>
		<category><![CDATA[Spring/SpringBoot]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[springboot]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=650</guid>

					<description><![CDATA[In the following article, apart from providing two solutions to the title problem, we will also talk about a few side topics. I find them worth discussing as they explain the specific behavior of SpringBoot and the H2 database when running JUnit tests.]]></description>
										<content:encoded><![CDATA[
<p>In the following article, apart from providing two solutions to the title problem, we will also talk about a few side topics. I find them worth discussing as they explain the specific behavior of SpringBoot and the H2 database when running JUnit tests.</p>



<h2 class="wp-block-heading">TL;DR</h2>



<p>You can find a ready to use solution <a href="#solution">here</a> and on my <a rel="noreferrer noopener" href="https://gitlab.com/better-coding.com/public/java/java-sandbox/-/tree/main/h2-database-cleanup" target="_blank">GitLab</a>. However, I encourage you to read the whole article, because when coming up with the solution, I add many interesting digressions from the field of SpringBoot and the H2 database itself.</p>



<h2 class="wp-block-heading">Why clean the database at all during testing?</h2>



<p>Resetting the database state before running each test can be very useful when dealing with integration tests and Spring. Very often, in the case of integration tests, we use the in-memory H2 database, which allows us to test the JPA layer with a real database. The problem is that this instance of the database is run together with the Spring context being raised and it stores its state until the application is turned off. This causes problems with determining the state of the database before starting a given test and whether the state state does not affect the test result. Therefore, it would be much more convenient to clean the database before running each test case, to make sure that it executes under the same conditions every time. In the following, I will introduce two methods of resetting the database state and discuss the pros and cons of each.</p>



<h2 class="wp-block-heading">Sample test case</h2>



<p>To better illustrate the described problem, I have prepared the following test. Notice that we have two test methods in it. Each of them adds a book to the book repository and checks that there is exactly one book in the repository after each test case.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="H2DatabaseCleanupTests.java" data-enlighter-group="g1">package com.bettercoding.h2databasecleanup;

import com.bettercoding.h2databasecleanup.db.Book;
import com.bettercoding.h2databasecleanup.helper.BookRepositoryHelper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
class H2DatabaseCleanupTests {

    @Autowired
    private BookRepositoryHelper bookRepositoryHelper;


    @Test
    void firstTest() {
        //given
        Book book = new Book(UUID.randomUUID().toString(), "A Passage to India", "E.M. Foster");
        //when
        bookRepositoryHelper.addBook(book);
        // then
        assertEquals(1, bookRepositoryHelper.findAllBooks().size());
    }

    @Test
    void secondTest() {
        //given
        Book book = new Book(UUID.randomUUID().toString(), "A Revenue Stamp", "Amrita Pritam");
        //when
        bookRepositoryHelper.addBook(book);
        // then
        assertEquals(1, bookRepositoryHelper.findAllBooks().size());
    }


}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="BookRepositoryHelper.java" data-enlighter-group="g1">package com.bettercoding.h2databasecleanup.helper;

import com.bettercoding.h2databasecleanup.db.Book;
import com.bettercoding.h2databasecleanup.db.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.List;

@Component
public class BookRepositoryHelper {
    @Autowired
    BookRepository bookRepository;

    @Transactional
    public void addBook(Book book) {
        bookRepository.save(book);
    }

    @Transactional
    public List&lt;Book> findAllBooks() {
        return bookRepository.findAll();
    }
}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="Book.java" data-enlighter-group="g1">package com.bettercoding.h2databasecleanup.db;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.annotation.processing.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Getter
@Setter
@NoArgsConstructor
@Entity
@AllArgsConstructor
public class Book {
    @Id
    private String id;

    @Column
    private String title;

    @Column
    private String author;
}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="BookRepository.java" data-enlighter-group="g1">package com.bettercoding.h2databasecleanup.db;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository&lt;Book, String> {
}
</pre>



<p>After running the test, it turns out that the second test case fails, because in the repository, apart from the newly added book, there is another one &#8211; added in the first test case. Of course, we can write this test in such a way that it is resistant to the already existing data, but in the case of more complex tests, it is more convenient to start with a clean application and create exactly the conditions we want.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_1-1024x665.jpg" alt="" class="wp-image-661" srcset="https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_1-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_1-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_1-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_1.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">1st Method: @DirtiestContext</h2>



<p>SpringBoot has implemented a mechanism of reusing contexts for testing purposes. I will not deep into its detailed description here because out of the scope of this article. It is important to know that if a test class does not differ significantly from another (e.g. it does not have additional beans or other configuration elements), SpringBoot can very quickly deliver a clean copy of the context from a special cache instead of restarting the entire application. In our example, we are dealing with exactly this situation, so SpringBoot will start the context when running the first test case, add it to the cache and then execute the first test case. When the second test case runs, SpringBoot will provide us with a clean copy of the context from the cache &#8211; which is a very quick operation &#8211; instead of restarting the entire application. Unfortunately, the H2 database is not being re-created.</p>



<p>We can force SpringBoot not to use this context caching mechanism by adding the <strong>@DirtiestContext</strong> annotation to the test class. It is also important to force a new context to be started for each test case by adding <strong>@DirtiesContext (classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="H2DatabaseCleanupTests1.java" data-enlighter-group="g2">package com.bettercoding.h2databasecleanup;

import com.bettercoding.h2databasecleanup.db.Book;
import com.bettercoding.h2databasecleanup.helper.BookRepositoryHelper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;

import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class H2DatabaseCleanupTests1 {

    @Autowired
    private BookRepositoryHelper bookRepositoryHelper;


    @Test
    void firstTest() {
        //given
        Book book = new Book(UUID.randomUUID().toString(), "A Passage to India", "E.M. Foster");
        //when
        bookRepositoryHelper.addBook(book);
        // then
        assertEquals(1, bookRepositoryHelper.findAllBooks().size());
    }

    @Test
    void secondTest() {
        //given
        Book book = new Book(UUID.randomUUID().toString(), "A Revenue Stamp", "Amrita Pritam");
        //when
        bookRepositoryHelper.addBook(book);
        // then
        assertEquals(1, bookRepositoryHelper.findAllBooks().size());
    }


}
</pre>



<p>This solution is very easy to implement. Unfortunately, for each test case, the application is restarted, which, depending on the complexity of the application, may take from seconds to several dozen seconds. This may result in extending the test execution time to minutes or even hours. Please pay attention to the execution times of both test cases, which we will compare with the second discussed method.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_2-1024x665.jpg" alt="" class="wp-image-677" srcset="https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_2-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_2-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_2-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_2.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading" id="solution">2nd Method: TestExecutionListener that cleans database on every test case</h2>



<p>Let&#8217;s consider another way to reset the database state before running each test case, so as not to sacrifice the benefits of context caching. Here, the <strong>TestExecutionListener</strong> interface and the <strong>@TestExecutionListeners</strong> annotation come in handy, which allows you to connect to the JUnit test execution cycle and run your own code, e.g. before running a test case.</p>



<p>In the following, you will see the source code for the two <strong>CleanupH2DatabaseTestListener</strong> and <strong>CleanupH2DbService</strong> classes. The first one is responsible for joining the test execution cycle in such a way as to call the code responsible for cleaning the database, which was implemented in the <strong>CleanupH2DbService</strong> component. The discussed solution can be presented as follows:</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="701" height="401" src="https://better-coding.com/wp-content/uploads/2022/10/CleanupH2DatabaseTestListener.jpg" alt="" class="wp-image-656" srcset="https://better-coding.com/wp-content/uploads/2022/10/CleanupH2DatabaseTestListener.jpg 701w, https://better-coding.com/wp-content/uploads/2022/10/CleanupH2DatabaseTestListener-300x172.jpg 300w" sizes="auto, (max-width: 701px) 100vw, 701px" /></figure>



<p>There is one important problem in the process of deleting data in a relational database. Namely, we cannot delete the parent row as long as there are rows that refer to it. In practice, this means cleaning tables in the right order (in the case of a foreign key to the same table, it is even necessary to delete the rows in the right order).</p>



<p>Fortunately, we can use a trick to disable Constraint checking for a moment, so we will be able to delete the data in any order. After deletion is complete, turn on Constraint checking again. An additional step worth taking is resetting all sequences.</p>



<p>The last thing that remains for us to do is add the newly-implemented <strong>CleanupH2DatabaseTestListener</strong> to our test using the <strong>@TestExecutionListeners</strong> annotation. There is also a small catch here &#8211; we have to add <strong>DependencyInjectionTestExecutionListener</strong> to the list of custom listers. In other case Dependency Injection doesn&#8217;t work anymore in test. So let&#8217;s see the final solution that can also be found on <a rel="noreferrer noopener" href="https://gitlab.com/better-coding.com/public/java/java-sandbox/-/tree/main/h2-database-cleanup" target="_blank">my GitLab</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="22" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="CleanupH2DatabaseTestListener.java" data-enlighter-group="g3">package com.bettercoding.h2databasecleanup.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;

@Slf4j
public class CleanupH2DatabaseTestListener implements TestExecutionListener, Ordered {

    private static final String H2_SCHEMA_NAME = "PUBLIC";

    @Override
    public void beforeTestMethod(TestContext testContext) throws Exception {
        TestExecutionListener.super.beforeTestMethod(testContext);
        cleanupDatabase(testContext);
    }

    private void cleanupDatabase(TestContext testContext) {
        log.info("Cleaning up database begin");
        CleanupH2DbService cleanupH2DbService = testContext.getApplicationContext().getBean(CleanupH2DbService.class);
        cleanupH2DbService.cleanup(H2_SCHEMA_NAME);
        log.info("Cleaning up database end");
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="29-32" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="CleanupH2DbService.java" data-enlighter-group="g3">package com.bettercoding.h2databasecleanup.listener;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import javax.transaction.Transactional;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

@Component
@Slf4j
@RequiredArgsConstructor
public class CleanupH2DbService {
    public static final String H2_DB_PRODUCT_NAME = "H2";
    private final DataSource dataSource;

    @SneakyThrows
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public void cleanup(String schemaName) {
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement()) {
            if (isH2Database(connection)) {
                disableConstraints(statement);
                truncateTables(statement, schemaName);
                resetSequences(statement, schemaName);
                enableConstraints(statement);
            } else {
                log.warn("Skipping cleaning up database, because it's not H2 database");
            }
        }
    }

    private void resetSequences(Statement statement, String schemaName) {
        getSchemaSequences(statement, schemaName).forEach(sequenceName ->
                executeStatement(statement, String.format("ALTER SEQUENCE %s RESTART WITH 1", sequenceName)));
    }

    private void truncateTables(Statement statement, String schemaName) {
        getSchemaTables(statement, schemaName)
                .forEach(tableName -> executeStatement(statement, "TRUNCATE TABLE " + tableName));
    }

    private void enableConstraints(Statement statement) {
        executeStatement(statement, "SET REFERENTIAL_INTEGRITY TRUE");
    }

    private void disableConstraints(Statement statement) {
        executeStatement(statement, "SET REFERENTIAL_INTEGRITY FALSE");
    }

    @SneakyThrows
    private boolean isH2Database(Connection connection) {
        return H2_DB_PRODUCT_NAME.equals(connection.getMetaData().getDatabaseProductName());
    }

    @SneakyThrows
    private void executeStatement(Statement statement, String sql) {
        statement.executeUpdate(sql);
    }

    @SneakyThrows
    private Set&lt;String> getSchemaTables(Statement statement, String schemaName) {
        String sql = String.format("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES  where TABLE_SCHEMA='%s'", schemaName);
        return queryForList(statement, sql);
    }

    @SneakyThrows
    private Set&lt;String> getSchemaSequences(Statement statement, String schemaName) {
        String sql = String.format("SELECT SEQUENCE_NAME FROM INFORMATION_SCHEMA.SEQUENCES WHERE SEQUENCE_SCHEMA='%s'", schemaName);
        return queryForList(statement, sql);
    }

    @SneakyThrows
    private Set&lt;String> queryForList(Statement statement, String sql) {
        Set&lt;String> tables = new HashSet&lt;>();
        try (ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                tables.add(rs.getString(1));
            }
        }
        return tables;
    }
}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="17" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="H2DatabaseCleanupTests2.java" data-enlighter-group="g3">package com.bettercoding.h2databasecleanup;

import com.bettercoding.h2databasecleanup.db.Book;
import com.bettercoding.h2databasecleanup.helper.BookRepositoryHelper;
import com.bettercoding.h2databasecleanup.listener.CleanupH2DatabaseTestListener;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class, CleanupH2DatabaseTestListener.class})
class H2DatabaseCleanupTests2 {

    @Autowired
    private BookRepositoryHelper bookRepositoryHelper;


    @Test
    void firstTest() {
        //given
        Book book = new Book(UUID.randomUUID().toString(), "A Passage to India", "E.M. Foster");
        //when
        bookRepositoryHelper.addBook(book);
        // then
        assertEquals(1, bookRepositoryHelper.findAllBooks().size());
    }

    @Test
    void secondTest() {
        //given
        Book book = new Book(UUID.randomUUID().toString(), "A Revenue Stamp", "Amrita Pritam");
        //when
        bookRepositoryHelper.addBook(book);
        // then
        assertEquals(1, bookRepositoryHelper.findAllBooks().size());
    }


}
</pre>



<p>All that remains is to run the tests and check if the result matches the expected result. Please note how much faster the tests were performed compared to the previous method. Cleaning the database in this case took less than 4ms, which is a great result compared to the previous method which took around 130ms. However, it should be remembered that the first method is the overhead associated with the start of the application and depends on the number and time of loading beans, and the second method depends only on the number of tables and the amount of data. By this I mean that as the application becomes more complex, the first method will slow down significantly, while the second &#8211; regardless of conditions &#8211; will remain just as fast.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_3-1024x665.jpg" alt="" class="wp-image-673" srcset="https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_3-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_3-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_3-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/CleanH2Database_3.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="has-background" style="background-color:#d9edf7">To już wszystko co dla Ciebie przygotowałem w tym poradniku. <strong>Udostępnij proszę ten post</strong> aby pomóc mi dotrzeć do większego grona odbiorców. Dzięki i do zobaczenia w kolejnym poradniku.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Unity3D: Scrolling texture on Sprite(Image)</title>
		<link>https://better-coding.com/unity3d-scrolling-texture-on-spriteimage/</link>
					<comments>https://better-coding.com/unity3d-scrolling-texture-on-spriteimage/#respond</comments>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Sun, 16 Oct 2022 20:16:02 +0000</pubDate>
				<category><![CDATA[Unity3D]]></category>
		<category><![CDATA[unity]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=756</guid>

					<description><![CDATA[In this article, I will show you how you can scroll the texture on the Image object in Unity. This effect can be used, for example, to simulate a moving background or the parallax effect.]]></description>
										<content:encoded><![CDATA[
<p>In this article, I will show you how you can scroll the texture on the Image object in Unity. This effect can be used, for example, to simulate a moving background or the parallax effect.</p>



<h2 class="wp-block-heading">Resources</h2>



<p>Ready to use project you can find in <a href="https://gitlab.com/better-coding.com/public/unity-3d/unity-3d-sandbox/-/tree/main/ScrollTextureOnSprite">my GitLab</a>. If you prefer video you can find the tutorial on <a href="https://youtu.be/aPaN63Ys4to" target="_blank" rel="noreferrer noopener">my YouTube channel</a>.</p>



<h2 class="wp-block-heading">Prepare the scene</h2>



<p>Let&#8217;s start with preparing some nice texture that we want to scroll on sprite. In my case it is a night sky image with a size of 2048x2048px. After copying the texture to the Assets folder, it&#8217;s time to prepare the Canvas and Image objects. On Canvas Object I selected <strong>UI scale mode = Scale with screen size</strong> option and the resolution of 800x600px.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_1-1024x665.jpg" alt="" class="wp-image-762" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_1-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_1-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_1-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_1.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Then I adjust the Image to cover the entire visible area by centering the Image and setting the size to 1024x1024px. I assign the prepared texture of the night sky to the Image object.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_2-1024x665.jpg" alt="" class="wp-image-763" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_2-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_2-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_2-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_2.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Writing ScrollingTexture MonoBehaviour</h2>



<p>Now that we have a prepared test scene, it&#8217;s time to go trough to the implementation of the script responsible for scrolling the texture. Below I have presented one of its variants. I suggest that you read it before we dive into its detailed description, because there is a little hitch lurking there that is not obvious. I would like to add that apart from copying the script, the texture parameters must also be adjusted, which will be described in the next section.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ScrollTexture.java" data-enlighter-group="g1">using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class ScrollTexture : MonoBehaviour
{
    private Image _image;
    [SerializeField] private Vector2 speed;

    void Start()
    {
        _image = GetComponent&lt;Image>();
        _image.material = new Material(_image.material); //Clone the original material
    }

    void Update()
    {
        _image.material.mainTextureOffset += speed * Time.deltaTime;
    }
}</pre>



<p>We start the script analysis with the parameters displayed to the editor. In our case it is <strong>speed</strong>, which is a 2D vector and denotes the speed of scrolling in one second. The value of 1 means that the entire texture is scrolled in one second.</p>



<p>Let&#8217;s jump to the <strong>Update</strong> method for a moment. This is the heart of the script, and in it a fairly simple operation that updates the offset of the main texture by the product of <strong>speed</strong> and time &#8211; that is, the distance.</p>



<p>However, the most important part, is what happens in the <strong>Awake</strong> method, i.e. cloning the material assigned to our Image. Sprite 2D textures share one material instance. So if we update, for example, the <strong>mainTextureOffset</strong> property (as in our case), the effect of scrolling the texture will be applied to all Sprites that use it. In order for the texture scrolling effect to apply only to the object with the ScrollTexture component, it is necessary to create a copy of the material and assign it to the object. And this is what happens in the Awake method.</p>



<h2 class="wp-block-heading">Adding ScrollTexture script to the scene</h2>



<p>We add the script like any other component &#8211; by dragging it onto the selected GameObject.  Set the value of <strong>speed</strong> property to some low value &#8211; let&#8217;s say &#8211; 0.1 texture per second.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_3-1024x665.jpg" alt="" class="wp-image-765" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_3-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_3-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_3-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_3.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Texture adjusting</h2>



<p>If you have already run the simulation at this stage, you have probably noticed that the texture, after scrolling to the end, stretches the last pixels &#8211; drawing specific lines &#8211; instead of repeating itself.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_5-1024x665.jpg" alt="" class="wp-image-766" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_5-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_5-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_5-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_5.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>This specific effect is due to the default setting of the <strong>Wrap Mode = Clamp</strong> property on the texture. To achieve the repeating effect just change the <strong>Wrap Mode = Repeat</strong> on the texture of the sky. After sunning the simulation you should see nice texture scrolling effect.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="665" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_4-1024x665.jpg" alt="" class="wp-image-767" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_4-1024x665.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_4-300x195.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_4-768x499.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_4-1536x998.jpg 1536w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_scrolling_texture_4-2048x1330.jpg 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://better-coding.com/unity3d-scrolling-texture-on-spriteimage/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Unity 3D: Can’t see Cinemachine in C# script</title>
		<link>https://better-coding.com/unity-3d-cant-see-cinemachine-in-c-script/</link>
					<comments>https://better-coding.com/unity-3d-cant-see-cinemachine-in-c-script/#respond</comments>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Sun, 09 Oct 2022 21:35:56 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Unity3D]]></category>
		<category><![CDATA[unity]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=623</guid>

					<description><![CDATA[There might be two main reasons why you can’t see Cinemachine in your C# script – missing Cinemachine package or missing assembly reference. In the following article you will find solution for both causes.]]></description>
										<content:encoded><![CDATA[
<p>There might be two main reasons why you can&#8217;t see <strong>Cinemachine</strong> in your C# script &#8211; missing Cinemachine package or missing assembly reference. In the following article you will find solution for both causes.</p>



<h2 class="wp-block-heading">1. Missing Cinemachine package</h2>



<p>At first, ensure that you have installed <strong>Cinemachine</strong> package in your unity project. <strong>Open Window -&gt; Package Manager </strong>and choose <strong>Packages in project</strong> from the top menu. If you have not installed <strong>Cinamechine</strong> just switch to <strong>Unity Registry</strong> from the top menu, search for<strong> Cinemachine</strong> and install it.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="612" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_install_cinemachine-1024x612.jpg" alt="" class="wp-image-628" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_install_cinemachine-1024x612.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_install_cinemachine-300x179.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_install_cinemachine-768x459.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_install_cinemachine.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">2. Missing assembly reference</h2>



<p>If you have an assembly definition file in your project ensure that you have linked <strong>com.unity.cinemachine</strong> assembly to it. In the following case I created a <strong>Main.afmdef </strong>file in on of the directory of my project. Try to locate the assembly definition file in your project going up from the directory contains the problematic script. Select the assembly definition file and add <strong>Assembly Definition Reference</strong> to the list as it is shown below.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="469" src="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_cinemachine_add_assembly_reference-1024x469.jpg" alt="" class="wp-image-630" srcset="https://better-coding.com/wp-content/uploads/2022/10/Unity3d_cinemachine_add_assembly_reference-1024x469.jpg 1024w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_cinemachine_add_assembly_reference-300x138.jpg 300w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_cinemachine_add_assembly_reference-768x352.jpg 768w, https://better-coding.com/wp-content/uploads/2022/10/Unity3d_cinemachine_add_assembly_reference.jpg 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://better-coding.com/unity-3d-cant-see-cinemachine-in-c-script/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>FiveM + C#: Storing player data in MySQL/MariaDB database. Complete guide from scratch.</title>
		<link>https://better-coding.com/fivem-c-storing-player-data-in-mysql-mariadb-database-complete-guide-from-scratch/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Mon, 09 May 2022 23:27:10 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[fivem]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=467</guid>

					<description><![CDATA[The following video shows how to create both client and server scripts for FiveM that allows you to pass data from the client through the server and to store it in MySQL database]]></description>
										<content:encoded><![CDATA[
<p>The following video shows how to create both client and server scripts for FiveM that allows you to pass data from the client through the server and to store it in MySQL database. The tutorial consists of the following parts:<ins></ins></p>



<ol class="wp-block-list">
<li>Prepare basic client and server C# projects. In the following step I show you how to set dependency between mentioned projects, to force right build order and then to perform copy result artefacts to the game resources directory.</li>



<li>Create simple working FiveM plug-ins. From this part of the tutorial you will learn how to create very basic pair of plug-ins – client and server side.</li>



<li>Passing data from the game client to the FiveM server. In the following step you will register a client command, that displays chat message on the screen. After that you enrich it with ability to emit event to the server. At the end, you will display the received message to the sever console.</li>



<li>In the final step of our journey, you will start from creating MySQL connection to the real database. After that you will use it to call insert statement that allows you to store data in the database.</li>
</ol>



<p><a href="https://www.youtube.com/watch?v=A7JM_puWyXU" target="_blank" rel="noreferrer noopener">Here you can find the video version of the tutorial</a></p>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Ionic &amp; Angular: Custom page transitions (animations between pages)</title>
		<link>https://better-coding.com/ionic-angular-custom-page-transitions-animations-between-pages/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Mon, 09 May 2022 23:14:21 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Ionic]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[ionic]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=457</guid>

					<description><![CDATA[Default page transitions that you can find in out of the box Ionic framework does not always suits your needs. In some cases you may want to have custom page animations when ion-router-outlet navigates between pages. Let me share with you a very compact and elegant solution for the title topic.]]></description>
										<content:encoded><![CDATA[
<p>Default page transitions that you can find in out of the box Ionic framework does not always suits your needs. In some cases you may want to have custom page animations when ion-router-outlet navigates between pages. Let me share with you a very compact and elegant solution for the title topic.</p>



<h2 class="wp-block-heading">Watch the tutorial on YouTube</h2>



<p><a href="https://youtu.be/wV-fDUI-5LQ" target="_blank" rel="noreferrer noopener">Here you can find the video version of the tutorial.</a></p>



<h2 class="wp-block-heading">How to implement a custom page transition in Ionic with Angular</h2>



<p>Lets suppose that you want to add fade out effect to all page transitions in your Ionic application. The best place to customize animation for this purpose is <strong>ion-router-outlet</strong>. According to the&nbsp;<a href="https:https://ionicframework.com/docs/api/router-outlet" target="_blank" rel="noreferrer noopener">Ionic documentation</a>&nbsp;you can pass a custom function as the “animation” property of <strong>ion-router-outlet</strong>.</p>



<p>Edit&nbsp;<strong>app.component.html</strong>&nbsp;file and set “myCustomPageTransition” value as the animation property of&nbsp;<strong>ion-router-outlet</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="app.component.html" data-enlighter-group="g1">&lt;ion-app>
  &lt;ion-router-outlet [animation]="myCustomPageTransition">&lt;/ion-router-outlet>
&lt;/ion-app></pre>



<p>Then edit&nbsp;<strong>app.component.ts</strong>&nbsp;file and create&nbsp;<strong>myCustomPageTransition</strong>&nbsp;property as is shown below. Please not that you can use both enteringEl and leavingEl in your animation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="typescript" data-enlighter-theme="" data-enlighter-highlight="13-33" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="app.component.ts" data-enlighter-group="g2">import { Component } from '@angular/core';

import { AnimationController, Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
myCustomPageTransition = ((baseEl: any, opts?: any) => { 
    console.log("opts.enteringEl:"  + opts.enteringEl); //Entering Element - New Page
    console.log("opts.leavingEl:"  + opts.leavingEl);   //Leaving Element - Current Page
    var anim1 = this.animationCtrl.create()
      .addElement(opts.leavingEl)
      .duration(2000)
      .iterations(1)
      .easing('ease-out')
      .fromTo('opacity', '1', '0.0')
    var anim2 = this.animationCtrl.create()
      .addElement(opts.enteringEl)
      .duration(2000)
      .iterations(1)
      .easing('ease-out')
      .fromTo('opacity', '0.0', '1')
     var anim2 = this.animationCtrl.create()
      .duration(2000)
      .iterations(1)
      .addAnimation([anim1, anim2]);
    return anim2;
});

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private animationCtrl: AnimationController
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
}</pre>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Java thread-safe singleton pattern (with and without lazy loading)</title>
		<link>https://better-coding.com/java-thread-safe-singleton-pattern-with-and-without-lazy-loading/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Fri, 06 May 2022 23:14:05 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=409</guid>

					<description><![CDATA[In the first part of the guide you get know the right solution to implement thread safe singleton in Java. Then I'm going to explain to you what's wrong with the most common singleton implementation and why it is not thread safe. ]]></description>
										<content:encoded><![CDATA[
<p>In the first part of the guide you get to know the right solution to implement thread safe singleton in Java. Then I&#8217;m going to explain to you what&#8217;s wrong with the most common singleton implementation and why it is not thread safe. </p>



<h2 class="wp-block-heading">Resources</h2>



<p><a href="https://gitlab.com/better-coding.com/public/java/java-sandbox/-/tree/main/java-singletons" target="_blank" rel="noreferrer noopener">GitLab: java-singletons</a></p>



<h2 class="wp-block-heading">Java thread safe singleton implementation without lazy loading</h2>



<p>The easiest and thread safe singleton implementation in Java is to use enum class. It might be not intuitive but it works perfect if you don&#8217;t need lazy loading. Enum instances are guaranteed to be created exactly once that you don&#8217;t have to worry about thread safe initialization. So let&#8217;s see how the implementation looks like in the following example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="DummySingleton.java" data-enlighter-group="g1">public enum DummySingleton {
    INSTANCE;

    public static DummySingleton getInstance() {
        return INSTANCE;
    }

    //This is dummy singleton's field
    private String dummyField = "Hello World!";

    //This is dummy singleton's method
    public void dummyMethod(String stringParam) {
        this.dummyField = stringParam;
    }

    //This is dummy singleton's method
    public String getDummyField() {
        return this.dummyField;
    }
}
</pre>



<h2 class="wp-block-heading">Java thread safe singleton with lazy loading</h2>



<p>In case, you need a thread safe singleton with lazy loading you can use the following pattern. As you can see, it consists of a double check of the singleton instance, to check if it is null. The first one is not synchronized so it&#8217;s fast and each thread can access it without additional synchronization cost. When the singleton instance returns to null then the synchronized initialization of the singleton starts to happens in order to ensure that exactly one instance of the class has been created.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="5-11" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="DummySingletonWithLazyLoading.java" data-enlighter-group="g2">public final class DummySingletonWithLazyLoading {
    private static DummySingletonWithLazyLoading instance = null;

    public static DummySingletonWithLazyLoading getInstance() {
        if (instance  == null ) {
            synchronized (DummySingletonWithLazyLoading.class) {
                if (instance  == null ) {
                    instance = initializeSingletonInstance();
                }
            }
        }
        return instance;
    }

    private DummySingletonWithLazyLoading() {
    }

    private static DummySingletonWithLazyLoading initializeSingletonInstance() {
        return new DummySingletonWithLazyLoading();
    }

    //This is dummy singleton's field
    private String dummyField = "Hello World!";

    //This is dummy singleton's method
    public void dummyMethod(String stringParam) {
        this.dummyField = stringParam;
    }

    //This is dummy singleton's method
    public String getDummyField() {
        return this.dummyField;
    }
}</pre>



<h2 class="has-pale-pink-color has-text-color wp-block-heading">Non thread safe single null check singleton implementation</h2>



<p>In the last part I would like to explain to you why one of the most common singleton implementation is not threqd safe. Let&#8217;s have look at the following example. I intentionally modified the initialization time of the first singleton instance to emphasize what may happened in that scenario in multithreading environment. So let&#8217;s suppose that two threads run almost in the same time.  From perspective of the first thread it run  <strong>line 8</strong> and because the <strong>instance</strong> is equal to null it run <strong>line 9</strong>. Then it have to wait some time for constructing the object (I my case it is 2000ms) then the reference of the object is assigned to <strong>instance</strong>. If the second thread runs <strong>line 8</strong> during the first thread is waiting for the object construction the condition in the <strong>line 8</strong> returns true, so the second thread starts to execute <strong>line 9</strong>. In that way two instances of the singleton were created instead of one. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="8-10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="NonThreadSafeDummySingleton.java" data-enlighter-group="g3">import java.util.concurrent.atomic.AtomicInteger;

public class NonThreadSafeDummySingleton {
    public static final AtomicInteger TOTAL_INSTANCES = new AtomicInteger();
    private static NonThreadSafeDummySingleton instance;

    public static NonThreadSafeDummySingleton getInstance() {
        if (instance == null) {
            instance = new NonThreadSafeDummySingleton();
        }
        return instance;
    }

    public NonThreadSafeDummySingleton() {
        final int currentInstance = TOTAL_INSTANCES.incrementAndGet();
        System.out.println("Creating NonThreadSafeDummySingleton instance number: " + currentInstance);
        if (currentInstance == 1) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("NonThreadSafeDummySingleton instance number: " + currentInstance + " created");
    }
}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="NonThreadSafeDummySingletonTest.java" data-enlighter-group="g3">import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import static org.junit.jupiter.api.Assertions.*;

class NonThreadSafeDummySingletonTest {
    @Test
    void doubleInstanceCreatedTest() {
        //given
        CompletableFuture&lt;Void> c1 = CompletableFuture.supplyAsync(() -> {
            NonThreadSafeDummySingleton.getInstance();
            return null;
        });

        CompletableFuture&lt;Void> c2 = CompletableFuture.supplyAsync(() -> {
            NonThreadSafeDummySingleton.getInstance();
            return null;
        });

        List&lt;CompletableFuture> all = List.of(c1, c2);
        //when
        all.forEach(CompletableFuture::join);
        //then
        assertEquals(2, NonThreadSafeDummySingleton.TOTAL_INSTANCES.get());
    }
}</pre>



<p>You can run the above test to ensure the wrong behaviour of the singleton implementation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Creating NonThreadSafeDummySingleton instance number: 2
Creating NonThreadSafeDummySingleton instance number: 1
NonThreadSafeDummySingleton instance number: 2 created
NonThreadSafeDummySingleton instance number: 1 created</pre>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Java &amp; SpringBoot: Overriding system time for Unit, Integration and End2End testing – Complete guide</title>
		<link>https://better-coding.com/java-springboot-overriding-system-time-for-unit-integration-and-end2end-testing-complete-guide/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Thu, 05 May 2022 19:40:52 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring/SpringBoot]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[springboot]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=262</guid>

					<description><![CDATA[Have you ever wondering how to make your application travel in time? If you have, let me tell you that’s great because in the following tutorial I’m going to show you in the real examples how to manage time for all of three test layers - unit tests, integration tests and end-to-end testing.]]></description>
										<content:encoded><![CDATA[
<p>Have you ever wondering how to make your application travel in time? If you have, let me tell you that’s great because in the following tutorial I’m going to show you in the real examples how to manage time for all of three test layers &#8211; unit tests, integration tests and end-to-end testing.</p>



<h2 class="wp-block-heading">Resources</h2>



<ul class="wp-block-list">
<li><a rel="noreferrer noopener" href="https://gitlab.com/better-coding.com/public/java/java-sandbox/-/tree/main/time-traveling-demo" target="_blank">GitLab: time-traveling-demo</a></li>



<li><a href="https://youtu.be/R33-3ImJpHk" target="_blank" rel="noreferrer noopener">Video tutorial on YouTube</a></li>
</ul>



<h2 class="wp-block-heading">Overview</h2>



<p>Let’s think for a moment how we can test the behaviour of our application in different points of time. </p>



<p>The most obvious way is just to wait for time to pass by. But it’s not optimal solution and I think that I don’t have to explain it to you why.</p>



<p>Another solution is targeted to applications that you don’t have control over. It requires to modify bytecode using AspectJ in the way that all of getting time invocations return custom point in time, but it’s not covered in this tutorial.</p>



<p>The last way is targeted to applications that you have full control over. It’s to replace all of the getting time invocations (like LocalDateTime.now(), new Date() … etc) by invoking a custom DateTime provider. It’s very simple solution but it’s easy to implement and it works perfect.</p>



<h2 class="wp-block-heading">Sample application</h2>



<p>For the tutorial purposes I prepared simple SpringBoot application consists of <strong>TimeController</strong> exposed on the <strong>localhost:8080/time</strong> REST endpoint. It returns current time from <strong>BigBen</strong> bean which is responsible for returning current time in the application.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="TimeController.java" data-enlighter-group="g1">package com.bettercoding.timetraveling.timetravelingdemo;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZonedDateTime;

@RestController
@RequestMapping("/time")
@RequiredArgsConstructor
public class TimeController {
    private final BigBen bigBen;

    @GetMapping("/")
    public ZonedDateTime getCurrentTime() {
        return bigBen.getApplicationTime();
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="BigBen.java" data-enlighter-group="g1">package com.bettercoding.timetraveling.timetravelingdemo;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.ZonedDateTime;

@Component
@RequiredArgsConstructor
public class BigBen {
    public ZonedDateTime getApplicationTime() {
        return ZonedDateTime.now();
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="TimeTravelingDemoApplication.java" data-enlighter-group="g1">package com.bettercoding.timetraveling.timetravelingdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TimeTravelingDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(TimeTravelingDemoApplication.class, args);
	}

}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="pom.xml" data-enlighter-group="g1">&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	&lt;modelVersion>4.0.0&lt;/modelVersion>
	&lt;parent>
		&lt;groupId>org.springframework.boot&lt;/groupId>
		&lt;artifactId>spring-boot-starter-parent&lt;/artifactId>
		&lt;version>2.6.6&lt;/version>
		&lt;relativePath/> &lt;!-- lookup parent from repository -->
	&lt;/parent>
	&lt;groupId>com.bettercoding.timetraveling&lt;/groupId>
	&lt;artifactId>time-traveling-demo&lt;/artifactId>
	&lt;version>0.0.1-SNAPSHOT&lt;/version>
	&lt;name>time-traveling-demo&lt;/name>
	&lt;description>Demo project of time traveling Spring Boot application&lt;/description>
	&lt;properties>
		&lt;java.version>17&lt;/java.version>
	&lt;/properties>
	&lt;dependencies>
		&lt;dependency>
			&lt;groupId>org.springframework.boot&lt;/groupId>
			&lt;artifactId>spring-boot-starter-web&lt;/artifactId>
		&lt;/dependency>

		&lt;dependency>
			&lt;groupId>org.projectlombok&lt;/groupId>
			&lt;artifactId>lombok&lt;/artifactId>
			&lt;optional>true&lt;/optional>
		&lt;/dependency>
		&lt;dependency>
			&lt;groupId>org.springframework.boot&lt;/groupId>
			&lt;artifactId>spring-boot-starter-test&lt;/artifactId>
			&lt;scope>test&lt;/scope>
		&lt;/dependency>
	&lt;/dependencies>

	&lt;build>
		&lt;plugins>
			&lt;plugin>
				&lt;groupId>org.springframework.boot&lt;/groupId>
				&lt;artifactId>spring-boot-maven-plugin&lt;/artifactId>
				&lt;configuration>
					&lt;excludes>
						&lt;exclude>
							&lt;groupId>org.projectlombok&lt;/groupId>
							&lt;artifactId>lombok&lt;/artifactId>
						&lt;/exclude>
					&lt;/excludes>
				&lt;/configuration>
			&lt;/plugin>
		&lt;/plugins>
	&lt;/build>

&lt;/project></pre>



<h2 class="wp-block-heading">DateTimeProvider implementation</h2>



<p>I decided to implement the following <strong>DateTImeProvider</strong> as a thread-safe Singleton. The easiest way to achieve it it to use enum class. <strong>DateTimeProvider</strong> consists of the internal clock, and following methods:&nbsp;</p>



<ul class="wp-block-list">
<li>timeNow() &#8211; returns current time, based on internal clock</li>



<li>setTime() &#8211; sets the internal clock as fix time or custom clock passed as parameter</li>



<li>resetTime()&nbsp;&#8211; resets the internal clock to the default one.</li>
</ul>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="DateTimeProvider.java" data-enlighter-group="g2">package com.bettercoding.timetraveling.timetravelingdemo;

import java.time.Clock;
import java.time.ZonedDateTime;

public enum DateTimeProvider {
    INSTANCE;

    public static DateTimeProvider getInstance() {
        return INSTANCE;
    }

    private final Clock defaultClock = Clock.systemDefaultZone();
    private Clock clock = defaultClock;

    public ZonedDateTime timeNow() {
        return ZonedDateTime.now(clock);
    }

    public void setTime(ZonedDateTime zonedDateTime) {
        var customClock = Clock.fixed(zonedDateTime.toInstant(), zonedDateTime.getZone());
        this.setTime(customClock);
    }

    public void setTime(Clock clock) {
        this.clock = clock;
    }

    public void resetTime() {
        this.clock = this.defaultClock;
    }

}</pre>



<p>What we have to do now is to replace all of getting time invocations(LocalDateTime, new Date(), etc…) by invoking <strong>DateTimeProvider.getInstance().timeNow()</strong>. So let&#8217;s modify <strong>BigBen</strong> class to use the implemented <strong>DateTimeProvider</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="BigBen.java" data-enlighter-group="g1a">package com.bettercoding.timetraveling.timetravelingdemo;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.ZonedDateTime;

@Component
@RequiredArgsConstructor
public class BigBen {

    public ZonedDateTime getApplicationTime() {
        return DateTimeProvider.getInstance().timeNow();
    }
}</pre>



<h2 class="wp-block-heading">Changing time in Unit Tests</h2>



<p>Managing the time in UnitTest is very simple, the only thing you have to do is just to invoke <strong>DateTimeProvider.getInstance().setTime()</strong> before unit test. It’s very important to <strong>resetTime()</strong> after execution of unit tests because modified time may affect on the other unit tests. Please remember that you cannot run time traveling tests in parallel, because time set in one thread may be overridden by another thread.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="BigBenTimeTravelingUnitTest.java" data-enlighter-group="g3">package com.bettercoding.timetraveling.timetravelingdemo;


import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class BigBenTimeTravelingUnitTest {

    @BeforeAll
    static void setup() {
        ZonedDateTime customAppTime = ZonedDateTime.parse("1990-01-02T11:00:56+02:00", DateTimeFormatter.ISO_ZONED_DATE_TIME);
        DateTimeProvider.getInstance().setTime(customAppTime);
    }

    @AfterAll
    static void cleanup() {
        DateTimeProvider.getInstance().resetTime();
    }

    @Test
    void timeTravelingTest() {
        //given
        ZonedDateTime expectedTime = ZonedDateTime.parse("1990-01-02T11:00:56+02:00", DateTimeFormatter.ISO_ZONED_DATE_TIME);
        BigBen bigBen = new BigBen();
        //when
        var applicationTime = bigBen.getApplicationTime();
        //then
        Assertions.assertEquals(expectedTime, applicationTime);
    }
}</pre>



<h2 class="wp-block-heading">Managing the time in Integration Tests</h2>



<p>Let’s modify <strong>BigBen</strong> class to use <strong>DateTimeProvider</strong> bean instead of invoking <strong>DateTimeProvider.getInstance().timeNow()</strong> directly. This step is not necessary, but I would like to show you, that you can do it too.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="11,14" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="BigBen.java" data-enlighter-group="g1b">package com.bettercoding.timetraveling.timetravelingdemo;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.ZonedDateTime;

@Component
@RequiredArgsConstructor
public class BigBen {
    private final DateTimeProvider dateTimeProvider;

    public ZonedDateTime getApplicationTime() {
        return dateTimeProvider.timeNow();
    }
}</pre>



<p>Before you you run the application you have to provide <strong>DateTimeProvider</strong> bean configuration. Please, don’t mark <strong>DateTimeProvider</strong> as a component. It’s very important to create a custom bean configuration that you return <strong>DateTimeProvider.getInstance() </strong>instead creating new instance.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="TimeConfiguration.java" data-enlighter-group="g3a">package com.bettercoding.timetraveling.timetravelingdemo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TimeConfiguration {
    @Bean
    DateTimeProvider dateTimeProvider() {
        return DateTimeProvider.getInstance();
    }
}</pre>



<p>If you made all of the previous steps you can modify the time in the similar way as you made it in the unit tests case.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="TimeTravelingDemoApplicationTests.java" data-enlighter-group="g3b">package com.bettercoding.timetraveling.timetravelingdemo;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@SpringBootTest
class TimeTravelingDemoApplicationTests {
	@Autowired
	private BigBen bigBen;

	@BeforeAll
	static void setup() {
		ZonedDateTime customAppTime = ZonedDateTime.parse("1990-01-02T11:00:56+02:00", DateTimeFormatter.ISO_ZONED_DATE_TIME);
		DateTimeProvider.getInstance().setTime(customAppTime);
	}

	@AfterAll
	static void cleanup() {
		DateTimeProvider.getInstance().resetTime();
	}

	@Test
	void contextLoads() {
	}

	@Test
	void timeTravelTest() {
		//given
		ZonedDateTime expectedTime = ZonedDateTime.parse("1990-01-02T11:00:56+02:00", DateTimeFormatter.ISO_ZONED_DATE_TIME);
		//when
		ZonedDateTime applicationTime = bigBen.getApplicationTime();
		//then
		Assertions.assertEquals(expectedTime, applicationTime);
	}

}
</pre>



<h2 class="wp-block-heading">Managing time in End2End testing</h2>



<p>End2End testing is usually performed in some test environment that our application exists in and it is managed by some external application (for example TestNg and Selenium based application). Let’s call it <strong>End2EndTestPlayer</strong>. The application is responsible for playing a test scenario across tested applications.&nbsp;</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="431" height="191" src="https://better-coding.com/wp-content/uploads/2022/05/E2EtestPlayer.jpg" alt="" class="wp-image-411" srcset="https://better-coding.com/wp-content/uploads/2022/05/E2EtestPlayer.jpg 431w, https://better-coding.com/wp-content/uploads/2022/05/E2EtestPlayer-300x133.jpg 300w" sizes="auto, (max-width: 431px) 100vw, 431px" /><figcaption class="wp-element-caption">End2EndTestPlayer plays some test scenario across multiple applications</figcaption></figure>



<p>The easiest way to test our application in such environment is to expose some <strong>REST</strong> endpoint that you can set and reset previously implemented <strong>DateDimeProvider</strong> externally. The following <strong>TimeManagementController</strong> exposes <strong>POST</strong> method on <strong>/time-management/</strong> resource that allows you to set the time in the application and it also exposes <strong>DELETE</strong> method for resetting the time.&nbsp;</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="586" height="238" src="https://better-coding.com/wp-content/uploads/2022/05/E2EtestPlayer-time-endpoint.jpg" alt="" class="wp-image-413" srcset="https://better-coding.com/wp-content/uploads/2022/05/E2EtestPlayer-time-endpoint.jpg 586w, https://better-coding.com/wp-content/uploads/2022/05/E2EtestPlayer-time-endpoint-300x122.jpg 300w" sizes="auto, (max-width: 586px) 100vw, 586px" /></figure>



<p>It’s not a good idea to always expose the TimeManagementController (for example in production environment) so you can add <strong>@ConditionalOnPropoerty </strong>annotation and use <strong>time-management.enable</strong> property to manage environments where the changing time feature should be enabled.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="TimeManagementController.java" data-enlighter-group="g4">package com.bettercoding.timetraveling.timetravelingdemo;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.time.ZonedDateTime;

@RestController
@RequestMapping("/time-management")
@ConditionalOnProperty(prefix = "time-management", name = "enabled", havingValue = "true")
@RequiredArgsConstructor
public class TimeManagementController {
    private final DateTimeProvider dateTimeProvider;

    @PostMapping("/")
    public void changeApplicationTime(@RequestBody ChangeApplicationTimeRequest changeApplicationTimeRequest) {
        this.dateTimeProvider.setTime(changeApplicationTimeRequest.getZonedDateTime());
    }

    @DeleteMapping
    public void resetApplicationTime() {
        this.dateTimeProvider.resetTime();
    }

    @Data
    private static class ChangeApplicationTimeRequest {
        ZonedDateTime zonedDateTime;
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="application.yml" data-enlighter-group="g4">time-management:
  enabled: true
</pre>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Spring: Injecting smaller scope bean into larger scope bean</title>
		<link>https://better-coding.com/spring-injecting-smaller-scope-bean-into-larger-scope-bean/</link>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Wed, 04 May 2022 12:37:04 +0000</pubDate>
				<category><![CDATA[Spring/SpringBoot]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[springboot]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=373</guid>

					<description><![CDATA[Let's build a coffee machine and then find out what happened if you inject a smaller scope bean into a larger scope bean. Spoiler: In the last part I'll tell you how to fix the coffee machine.]]></description>
										<content:encoded><![CDATA[
<p>Let&#8217;s build a coffee machine and then find out what happened if you inject a smaller scope bean into a larger scope bean. Spoiler: In the last part I&#8217;ll tell you how to fix the coffee machine.</p>



<h2 class="wp-block-heading">Resources</h2>



<p><a href="https://gitlab.com/better-coding.com/public/java/java-sandbox/-/tree/main/springboot-prototype-scope-inside-singleton" target="_blank" rel="noreferrer noopener">GitLab: springboot-prototype-scope-inside-singleton</a></p>



<h2 class="wp-block-heading">The Problem</h2>



<p>Let&#8217;s suppose that we have <strong>CoffeeMachine</strong> and <strong>DisposableCup</strong> components like below. We would like to achieve the effect that the <strong>CoffeeMachine</strong> always uses a new cup when brewing coffee, so that&#8217;s why we changed the default singleton to prototype scope on <strong>DisposableCup</strong> component.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="CoffeeMachine.java" data-enlighter-group="g1">package com.bettercoding.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CoffeeMachine {
    @Autowired
    public final DisposableCup disposableCup;

    public DisposableCup brewCoffee() {
        System.out.printf("Brewing coffee in [%s]\n", disposableCup.getName());
        return disposableCup;
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="DisposableCup.java" data-enlighter-group="g1">package com.bettercoding.demo;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
@Scope(scopeName = "prototype")
public class DisposableCup {
    private static final AtomicInteger TOTAL_CUPS = new AtomicInteger();
    private final String name;

    public DisposableCup() {
        this.name = "Disposable cup number " + TOTAL_CUPS.incrementAndGet();
    }

    public String getName() {
        return name;
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ScopesDemoApp.java" data-enlighter-group="g1">package com.bettercoding.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ScopesDemoApp implements CommandLineRunner {


    @Autowired
    private CoffeeMachine coffeeMachine;

    public static void main(String[] args) {
        SpringApplication.run(ScopesDemoApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        coffeeMachine.brewCoffee();
        coffeeMachine.brewCoffee();
        coffeeMachine.brewCoffee();
    }
}</pre>



<p>But&#8230; When we run the application we got the result like below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Brewing coffee in [Disposable cup number 1]
Brewing coffee in [Disposable cup number 1]
Brewing coffee in [Disposable cup number 1]</pre>



<p>As you can see <strong>CoffeeMachine</strong> uses the same cup instance for each brewing coffee. So what&#8217;s wrong with the code? The problem is understanding how Spring inject&#8217;s dependencies. It does it only once &#8211; during bean creation process. It means that once injected reference doesn&#8217;t change through the whole bean&#8217;s life even if the reference&#8217;s life scope is shorter than the bean&#8217;s life scope it is injected to. There is no difference if you use <strong>@Autowierd </strong>on a class field or you inject dependencies via class constructor.</p>



<h2 class="wp-block-heading">The solution</h2>



<p>In order for the CoffeeMachine to always use a new cup when brewing coffee you need to inject <strong>ObjectFactory&lt;DisposableCup></strong> and then just get necessary component instance from the factory. So let&#8217;s modify the CoffeMachine componet </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="9,13,15" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="CoffeeMachine.java" data-enlighter-group="g2">package com.bettercoding.demo;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CoffeeMachine {
    @Autowired
    public ObjectFactory&lt;DisposableCup> disposableCupObjectFactory;

    public DisposableCup brewCoffee() {
        DisposableCup aCup = disposableCupObjectFactory.getObject();
        System.out.printf("Brewing coffee in [%s]\n", aCup.getName());
        return aCup;
    }
}</pre>



<p>The last thing to do is to run the application again to ensure that everything works like we expect.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Brewing coffee in [Disposable cup number 1]
Brewing coffee in [Disposable cup number 2]
Brewing coffee in [Disposable cup number 3]</pre>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Spock: How to get Mock to return value to avoid NullPointerException or InvalidSpecException</title>
		<link>https://better-coding.com/spock-how-to-get-mock-to-return-value-to-avoid-nullpointerexception-or-invalidspecexception/</link>
					<comments>https://better-coding.com/spock-how-to-get-mock-to-return-value-to-avoid-nullpointerexception-or-invalidspecexception/#respond</comments>
		
		<dc:creator><![CDATA[lukasz.ciesla]]></dc:creator>
		<pubDate>Mon, 25 Apr 2022 22:15:28 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Testing]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spock]]></category>
		<guid isPermaLink="false">https://better-coding.com/?p=271</guid>

					<description><![CDATA[The following guide explains how to use mock in Spock Testing Framework in a proper way to get rid of unnecessary problems like NullPointerExceptions and InvalidSpecException when you try stubbing instead of mocking. ]]></description>
										<content:encoded><![CDATA[
<p>The following guide explains how to use mock in Spock Testing Framework in a proper way to get rid of unnecessary problems like NullPointerExceptions and InvalidSpecException when you try stubbing instead of mocking. </p>



<h2 class="wp-block-heading">The problem</h2>



<p>Let&#8217;s suppose that we have ShipmentService with <strong>delivery</strong> metod like below and we would like to test it. As you may see the <strong>delivery</strong> method  calls OrderService to get delivery metod selected for the specific order and then it calls <strong>orderService.setDeliveryStatus</strong> with different <strong>deliveryStatus</strong> depends on the <strong>deliveryMethod</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ShipmentService.java" data-enlighter-group="g1">public class ShipmentService {
    private final OrderService orderService;

    public ShipmentService(OrderService orderService) {
        this.orderService = orderService;
    }

    public void deliver(String orderId) {
        String deliveryMethod = orderService.getDeliveryMethod(orderId);
        if (deliveryMethod.equals("CAR")) {
            orderService.setDeliveryStatus("Delivered by CAR");
        } else {
            orderService.setDeliveryStatus("Unsupported delivery method");
        }
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="OrderService.java" data-enlighter-group="g1">public interface OrderService {
    String getDeliveryMethod(String orderId);

    void setDeliveryStatus(String deliveryMethod);
}</pre>



<p>Let&#8217;s try to create Spock test. When you run the following test you got NullPointerException in <strong>ShipmentService.java:10</strong>, because mocked <strong>orderService.getDeliveryMethod(orderId) </strong>returns <strong>null</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="" data-enlighter-highlight="11" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ShipmentServiceTest" data-enlighter-group="g2">import spock.lang.Specification

class ShipmentServiceTest extends Specification {
  def "delivery should set 'Delivered by CAR' status when order's delivery method is CAR"() {
    given:
      OrderService orderService = Mock()
      ShipmentService shipmentService = new ShipmentService(orderService)
    when:
      shipmentService.deliver("1")
    then:
      1 * orderService.getDeliveryMethod("1")
      1 * orderService.setDeliveryStatus("Delivered by CAR")
  }
}</pre>



<h2 class="wp-block-heading">Watch the solution on YouTube</h2>



<p><a href="https://youtu.be/Ww6a43HHG64" target="_blank" rel="noreferrer noopener">Here you can find the video version of the tutorial</a></p>



<h2 class="has-ast-global-color-0-color has-text-color wp-block-heading">Wrong solution</h2>



<p>The first thought to deal with it may be to use Stub instead of Mock, but it&#8217;s a dead end. Why? Let&#8217;s run the code below to find out.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="" data-enlighter-highlight="6,7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ShipmentServiceTest" data-enlighter-group="g3">import spock.lang.Specification

class ShipmentServiceTest extends Specification {
  def "delivery should set 'Delivered by CAR' status when order's delivery method is CAR"() {
    given:
      OrderService orderService = Stub()
      orderService.getDeliveryMethod("1") >> "CAR"
      ShipmentService shipmentService = new ShipmentService(orderService)
    when:
      shipmentService.deliver("1")
    then:
      1 * orderService.getDeliveryMethod("1")
      1 * orderService.setDeliveryStatus("Delivered by CAR")
  }
}</pre>



<p>Of course we got InvalidSpecException like below, because we cannot use Stub for testing interaction. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">org.spockframework.runtime.InvalidSpecException: Stub 'orderService' matches the following required interaction:

1 * orderService.getDeliveryMethod("1")   (0 invocations)

Remove the cardinality (e.g. '1 *'), or turn the stub into a mock.</pre>



<h2 class="wp-block-heading">Proper solution</h2>



<p>The right solution of the problem is to add return value <strong>&#8220;CAR&#8221;</strong> to place when we test the first interaction. It means that we expect exactly once invocation of <strong>orderService.getDeliveryMethod</strong> with argument <strong>&#8220;1&#8221;</strong> which should return mocked value <strong>&#8220;CAR&#8221;</strong> instead if null. More you can find in <a href="https://spockframework.org/spock/docs/2.1/all_in_one.html#_mocks" target="_blank" rel="noreferrer noopener">the official Spock documentation</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="" data-enlighter-highlight="6,11" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ShipmentServiceTest" data-enlighter-group="g3a">import spock.lang.Specification

class ShipmentServiceTest extends Specification {
  def "delivery should set 'Delivered by CAR' status when order's delivery method is CAR"() {
    given:
      OrderService orderService = Mock()
      ShipmentService shipmentService = new ShipmentService(orderService)
    when:
      shipmentService.deliver("1")
    then:
      1 * orderService.getDeliveryMethod("1") >> "CAR"
      1 * orderService.setDeliveryStatus("Delivered by CAR")
  }
}</pre>



<h2 class="wp-block-heading">Bonus: How to parametrize the test to cover all of the conditions</h2>



<p>In our case we can introduce <strong>orderDeliveryMethod</strong> and <strong>expectedDeliveryStatus</strong> parameters to paramtertize test input data and the expectation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="groovy" data-enlighter-theme="" data-enlighter-highlight="4, 11-16" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="ShipmentServiceTest" data-enlighter-group="g4">import spock.lang.Specification

class ShipmentServiceTest extends Specification {
  def "delivery should set '#expectedDeliveryStatus' status when order's delivery method is '#orderDeliveryMethod'"() {
    given:
      OrderService orderService = Mock()
      ShipmentService shipmentService = new ShipmentService(orderService)
    when:
      shipmentService.deliver("1")
    then:
      1 * orderService.getDeliveryMethod("1") >> orderDeliveryMethod
      1 * orderService.setDeliveryStatus(expectedDeliveryStatus)
    where:
      orderDeliveryMethod || expectedDeliveryStatus
      "CAR"               || "Delivered by CAR"
      "SHIP"              || "Unsupported delivery method"
  }
}</pre>



<p class="has-background" style="background-color:#d9edf7"><meta charset="utf-8">That&#8217;s all what I&#8217;ve prepared for you in this tutorial, if I helped you, <strong>please consider sharing this post</strong> to help me gain a wider audience.<br>Thanks and I hope to see you in my next tutorial.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://better-coding.com/spock-how-to-get-mock-to-return-value-to-avoid-nullpointerexception-or-invalidspecexception/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>