本文共 3187 字,大约阅读时间需要 10 分钟。
诚然,下面是根据您的要求优化的文章内容:
在需要编写简单测试时,可以直接编写 Junit 测试代码,适用于不需要 Spring Boot 功能的单元测试场景。
public class SimpleJunitTest { @Test public void testSayHi() { System.out.println("Hi Junit."); }} Spring Boot 提供了 spring-boot-starter-test 模块,用于执行应用程序的集成测试。使用 @SpringBootTest 注解可以自动识别主配置类,创建测试环境。
@SpringBootApplicationpublic class MysqlDataTestApplication { } 如果无法自动识别主配置类,可以手动指定类路径:
@SpringBootTest(classes = {MysqlDataTestApplication.class})public class MysqlDataTestApplicationTests { @Autowired private TOrderInfoService tOrderInfoService; @Test public void tOrderInfoServiceSelect() { TOrderInfo tOrderInfo = tOrderInfoService.selectByPrimaryKey(1L); Assertions.assertThat(tOrderInfo).isNotNull(); }} 如果需要启动完整的 HTTP 服务器,可以使用 @SpringBootTest 注解并设置 webEnvironment 参数:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)public class MysqlDataTestApplicationTests2 { @Autowired private TestRestTemplate restTemplate; @Test public void test() throws Exception { String response = restTemplate.getForObject("/query", String.class); Assertions.assertThat(response).contains("QRC123456789012"); }} 或者通过 @AutoConfigureMockMvc 假装无服务器环境执行测试:
@Autowiredprivate MockMvc mockMvc;@Testpublic void test() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/query")) .andExpect(MockMvcResultMatchers.status().isOk());} 单元测试通常使用 @Test 注解,主要用于验证单个类的行为。如果需要构建完整的 Spring 上下文,可以选择单元测试或集成测试。
使用 @MybatisTest 注解,可以将测试范围限定在 Mapper 层:
@MybatisTestpublic class TOrderInfoMapperTests { @Autowired private TOrderInfoMapper tOrderInfoMapper; @Test public void test3() { TOrderInfo orderInfo = new TOrderInfo(); orderInfo.setId(2L); orderInfo.setMerId("133333333"); int i = tOrderInfoMapper.updateByPrimaryKeySelective(orderInfo); Assertions.assertThat(i).isEqualTo(1); }} 在没有特殊要求的 Bean 测试中,可以使用默认的 @SpringBootTest 注解:
@SpringBootApplicationpublic class TOrderInfoServiceTest { @Configuration static class TOrderInfoServiceConfig { @Bean public TOrderInfoService cityService() { return new TOrderInfoService(); } } @Autowired private TOrderInfoService tOrderInfoService; @MockBean private TOrderInfoMapper tOrderInfoMapper; @Test public void test() { TOrderInfo tOrderInfo = new TOrderInfo(); tOrderInfo.setId(1L); tOrderInfo.setMerId("QRC123456789012"); Mockito.when(tOrderInfoMapper.selectByPrimaryKey(1L)) .thenReturn(tOrderInfo); TOrderInfo tOrderInfo1 = tOrderInfoService.selectByPrimaryKey(1L); Assertions.assertThat(tOrderInfo1).isNotNull(); }} MockMvc。MockMvc,用于模拟 HTTP 请求。希望这篇优化后的文章能够符合您的需求!
转载地址:http://ptptz.baihongyu.com/