Exploring integration testing best practices

While unit tests test a specific layer, integration tests are used to test the code in multiple layers. To keep the tests repeatable, we recommend that you use an embedded database instead of a real database for integration tests and create a separate profile for integration tests using an embedded database. This ensures that each developer has their own database to run the tests against. Let's look at a few simple examples.

This is an example of an application.properties file:

app.profiles.active: production

This is an example of an application-production.properties file:

    app.jpa.database: MYSQL
app.datasource.url: <<VALUE>>
app.datasource.username: <<VALUE>>
app.datasource.password: <<VALUE>>

And here is an example of an application-integration-test.properties file:

    app.jpa.database: H2
app.datasource.url=jdbc:h2:mem:mydb
app.datasource.username=sa
app.datasource.pool-size=30

We would need to include the H2 driver dependency in the test scope, as shown in the following snippet:

    <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>

An example integration test using @ActiveProfiles("integration-test") is as follows. The integration tests will now run using an embedded database:

    @ActiveProfiles("integration-test")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TodoControllerIT {

@LocalServerPort
private int port;

private TestRestTemplate template = new TestRestTemplate();

//Tests

}

Integration tests are critical for the continuous delivery of working software. The features that Spring Boot provides make it easy to implement integration tests.

For more details about implementing unit and integration tests with Spring Boot, we recommend reading Chapter 7, Unit Testing REST API with Spring Boot.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset