Test Database Down with Spring

Test Database Down with Spring

I need Spring tests for the app behavior during database(connection,down db..) error. Is there a way to shutdown/kill or start the H2 in-memory db from the Spring unit tests?

3 Answers

If testing DB connection, here is old, but still nice blog on the topic. You should be able to use TestContainers as well, for simpler DB creation.

If you need only test some failures on some exact actions (e.g. on repository save), you can simply mock the repository for the test run:

var mockedBean = Mockito.mock(MyRepository.class);
var originalBean = ReflectionTestUtils.getField(articleService, fieldName);
Mockito.when(mockedBean.save(Mockito.any(MyEntity.class))).thenThrow(new RuntimeException("My test exception"));
ReflectionTestUtils.setField(myService, fieldName, mockedBean);
...
// test here
...
// set bean back for other test cases
ReflectionTestUtils.setField(myService, fieldName, originalBean);

When running Junit tests with a h2 test database, then the database instance will start when the test suite starts running and stop when tests are done (assuming you've configured your database using beans).

If you're using spring-boot, then you can configure your h2 test database like:

src/test/resources/application-test.yml:

spring:
  datasource:
    driverClassName: org.h2.Driver
    url: jdbc:h2:mem:testdb
    username: sa
    password:

And configure your test like:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = "test")
public class SignupControllerTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Autowired
    private RealityKeeperRepository myrepo;

If you're using regular spring, then you can configure a DataSource bean with the @Profile("test") annotation:

@Bean
@Profile("test")
public DataSource devDataSource() {
    return new EmbeddedDatabaseBuilder()
        .setType(EmbeddedDatabaseType.HSQL)
        .build();
}

And configure your tests like:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
@ActiveProfiles(profiles = "test")
public class MyTest {
    @Autowired
    ...

Your AppConfig class should be annotated with @Configuration contain the devDataSource bean mentioned above.

Yes, if you have H2 dependency and DO NOT have settings for it, then Spring boot will start embedded H2 DB for you.

This article should be useful:

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.