用Java测试SQL数据库

问题描述 投票:0回答:1

我们有点卡在单元测试的一个点上。我们想测试一下,如果数据库服务器没有连接或无法访问会发生什么。我们已经编写了测试代码,但如果服务器没有连接,我们无法模仿。

这是我们目前的测试代码:

@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));
}

它有什么问题,或者丢失了?有人或任何人可以帮忙吗?

java unit-testing mockmvc
1个回答
0
投票

如果要测试此行为,则应为此方案编写集成测试。使用单元测试,您只想将特定类测试为一个Unit

您可以对单元测试执行的操作是,您自定义了服务层结果,以便抛出在无法访问数据库时将引发的异常。你可以这样做,例如(非常非常简单的例子btw):

@Test
public void testErrorInServiceWhileFetchingData() {

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

  // perform the controller call with MockMvc 

}

为此,您需要一些使用Mockito模拟对象的经验。有关使用Spring进行集成测试的更多信息,请查看令人敬畏的文档:https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing

© www.soinside.com 2019 - 2024. All rights reserved.