Spring Boot(23)单元测试——Mock

Spring Boot(23)单元测试——Mock

1. 模拟接口

功能:+两个字符串

2. 编写测试

说明:

  1. 分层编写test
  2. 一个小模块(单表)一个test
  3. service会进行空检测,null作为空白字符串处理

service:test

@SpringBootTest
class DemoServiceImplTest {
          
   
    @Autowired
    private DemoServiceImpl demoService;

    @MockBean
    private DemoManage demoManage;
    
    @Test
    void testAddOk() {
          
   
        Mockito.when(demoManage.add("a", "b")).thenReturn("ab");
        String c = demoService.add("a", "b");
        assert StringUtils.equals(c, "ab");
    }
 
    @Test
    void testAddFail() {
          
   
        Mockito.when(demoManage.add("a", "")).thenReturn("a");
        String c = demoService.add("a", null);
        assert StringUtils.equals(c, "a");
    }
}

controller:test

@SpringBootTest
@AutoConfigureMockMvc
class DemoControllerTest {
          
   
    @Autowired
    MockMvc mockMvc;

    @MockBean
    private DemoService demoService;

    @Test
    void testAddOk() throws Exception {
          
   
        Mockito.when(demoService.add("a", "b")).thenReturn("ab");
        String expect = "{"code": 0,"data":"ab"}";

        DemoDTO demoDTO = new DemoDTO();
        demoDTO.setA("a");
        demoDTO.setB("b");
        mockMvc.perform(MockMvcRequestBuilders.post("/demo/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(JSON.toJSONString(demoDTO)))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.content().json(expect));
    }

    @Test
    void testAddFail() throws Exception {
          
   
        Mockito.when(demoService.add("a", null)).thenReturn("a");
        String expect = "{"code": 0,"data":"a"}";

        DemoDTO demoDTO = new DemoDTO();
        demoDTO.setA("a");
        demoDTO.setB(null);
        mockMvc.perform(MockMvcRequestBuilders.post("/demo/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(JSON.toJSONString(demoDTO)))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.content().json(expect));
    }
}

补充

依赖:2.3.7,test中存在junit-jupiter-engine,需排除vintage

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
经验分享 程序员 微信小程序 职场和发展