0

We have kinda stuck in one point of unit testing. We would like to test, what happens if the database server is not connected or not reachable. We have already written the testcode, but we are not able to imitate, if the server is not connected.

Here is our current test code:

@Test
public void databaseIsNotRunning() throws Exception {
    mockMvc.perform(get("/heartbeat"))
            .andExpect(status().is5xxServerError())
            .andExpect(MockMvcResultMatchers.jsonPath("$.application-status").value("ok"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.database-status").value("error"))
            .andExpect(content().contentType(contentType));
}

What is wrong with it, or missing? Can someone or anyone help?

vdominika
  • 1
  • 1

1 Answers1

0

If you want to test this behaviour you should write an integration test for this scenario. With Unit tests you just want to test a specific class as one Unit.

What you could do with a Unit test is that you customized your service layer result to throw an exception that would be thrown if your database is not reachable. So you can do e.g. (very very simple example btw) :

@Test
public void testErrorInServiceWhileFetchingData() {

  when(myService.getData()).doThrow(new RuntimeException("Database not reachable"));

  // perform the controller call with MockMvc 

}

For this you need some experience in mocking objects with Mockito. For more information about integration testing with Spring have a look at the awesome documentation: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing

rieckpil
  • 10,470
  • 3
  • 32
  • 56