学习 Spring Boot(三):单元测试

配置

编辑 pom.xml 文件,添加依赖:

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>  

Mock 测试 Controller

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void test() throws Exception {
        User tom = new User();
        tom.setId(1);
        tom.setName("Tom");
        tom.setSex("m");

        User jerry = new User();
        jerry.setId(1);
        jerry.setName("Jerry");
        jerry.setSex("f");

        given(this.userService.queryAllUsers()).willReturn(Arrays.asList(tom, jerry));

        this.mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print());
    }

}