要编写一个测试来测试从数据库中检索数据的Spring Boot REST API,你可以使用JUnit和MockMvc来模拟HTTP请求和响应,并使用H2内存数据库来模拟实际的数据库。
首先,确保在你的项目的pom.xml文件中添加以下依赖项:
org.springframework.boot
spring-boot-starter-test
test
com.h2database
h2
test
然后,创建一个测试类,用于测试你的REST API。在这个测试类中,你可以使用@RunWith(SpringRunner.class)
注解将测试类与Spring Boot集成,并使用@SpringBootTest
注解加载应用程序的上下文。
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyRestControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testGetAllData() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/api/data"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$[0].id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("John"))
.andExpect(MockMvcResultMatchers.jsonPath("$[1].id").value(2))
.andExpect(MockMvcResultMatchers.jsonPath("$[1].name").value("Jane"));
}
}
以上代码中,setup()
方法使用MockMvcBuilders.webAppContextSetup()
来设置MockMvc
实例。testGetAllData()
方法使用perform()
方法来模拟GET请求,并使用andExpect()
方法来验证响应状态码和响应体中的数据。
最后,你需要在测试类上使用@AutoConfigureMockMvc
注解,以确保自动配置MockMvc
实例。
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyRestControllerTest {
// ...
}
现在,你可以运行这个测试类来测试你的Spring Boot REST API是否可以从数据库中检索数据。请确保在测试之前,你的应用程序已经正确配置了数据库连接和数据访问层。
上一篇:编写一个测试 WebSocketHandlerDecorator - 委托不能为空 的测试用例。
下一篇:编写一个测试类来测试java.lang.String类中的以下方法:length,charAt,substring,indexOf。