Integration testing

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.

We recommend that you 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 few simple examples.

The application.properties file:

    app.profiles.active: production

The application-production.properties file:

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

The 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 the @ActiveProfiles("integration-test") is shown 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 to be able to continuously deliver working software. The features Spring Boot provides make it easy to implement integration tests.

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

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