SpringBoot 测试

使用SpringBoot开发爽还是爽的,不过由于技术不精,被测试搞的头疼。今天就琢磨了一下如何使用Mockito进行测试。

简单的方法

springboot中

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc

public class ControllerTest {
    @Autowired
    MockMvc mockMvc;

}

下是Spring中的使用方法。

@RunWith(SpringRunner.class)   // Spring测试
@WebMvcTest()  // WebMvc测试,加上这个注解才能自动注入 MockMvc 组件
@ComponentScan(basePackages = {"top.taofoo.dict.web.*"})  //扫描组件
public class ControllerTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean  
    AnalysisService analysisService;



    @Test
    public void uploadTest() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.multipart("/analysis/upload")
                .file(new MockMultipartFile("file", new FileInputStream("C:\\Users\\taofu\\Desktop\\ss.xlsx"))));
    }

    @Test
    public void mvcTest() throws Exception {
        Mockito.when(analysisService.get()).thenReturn(Collections.singletonList(new Record("13", "434"))); //这里可以用 @Before单独抽出来
        mockMvc.perform(MockMvcRequestBuilders.get("/analysis/temp"))
                .andDo(mvcResult -> {
                    System.out.println(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8));
                })
                .andExpect(result -> {
                    assert result.getResponse().getStatus() == HttpServletResponse.SC_OK;
                });
    }
}

总结一下

  1. 三注解:@RunWith(SpringRunner.class)开启Spring测试, @MvcTest 注入Mock相关组件 ,@ComponentScan 包扫描

  2. 注入MockMvc组件

  3. @MockBean 注入Mock组件(就是自己想Mock的组件,会自动注入到容器中。类似 @Bean)

  4. 使用。@MockBean的组件可以自定义行为

还一种是使用SpringBoot的测试组件


@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebApplicationTests  {
    @Autowired
    TestRestTemplate restTemplate;

    @MockBean //依然可以使用MockBean
    AnalysisService analysisService;

    @Test
    void contextLoads() throws SQLException {
        Mockito.when(analysisService.get()).thenReturn(Arrays.asList(new Record("2", "43")));

        ResponseEntity<Result> res = restTemplate.getForEntity("/analysis/temp", Result.class);

        System.out.println(res);
    }


}

如何区分SpringBoot测试中的 Junit4 和 Junit5

在新版本的SpringBoot中 @SpringBootTest()使用的是 Junit5
而在@RunWith中使用的是JUnit4

https://zhuanlan.zhihu.com/p/162032557

posted @ 2021-06-07 14:47  Taofoo  阅读(427)  评论(0)    收藏  举报