欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot Controller单元测试的编写

程序员文章站 2022-04-29 16:39:13
...

单元测试是开发者针对目标代码编写的一小段代码,目的是为了确保我们目标代码与预期行为是一致的。以下是对一个Spring Boot小项目的Controller,进行的单元测试的简单编写:

//Controller
@RestController
public class UserController {
    @Resource
    private UserRepository userRepository;

    @PostMapping("/users")
    public String save(User user){
        userRepository.save(user);
        return "SUCCESS";
    }

    @DeleteMapping("/users/{id}")
    public String delete(@PathVariable(name = "id") Integer id){
        userRepository.deleteById(id);
        return "SUCCESS";
    }

    @GetMapping("/users/{id}")
    public User findOne(@PathVariable(name = "id") Integer id){
        return userRepository.findById(id).get();
    }

    @PutMapping("/users")
    public User update(User user){
        userRepository.save(user);
        return userRepository.getOne(user.getId());
    }
}

Controller层测试用例:

@RunWith(SpringRunner.class)
@SpringBootTest
//@ActiveProfiles("dev")加载特定配置文件
@AutoConfigureMockMvc
public class UserControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    @Transactional//测试环境下将自动进行回滚操作
    //@Rollback(false)
    public void testInsert() throws Exception {
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("/users");
        request.param("name","laiminghai");
        mvc.perform(request).
                andExpect(MockMvcResultMatchers.status().isOk()).
                andExpect(MockMvcResultMatchers.content().string("SUCCESS"));
    }

    @Test
    @Transactional
    //@Rollback(false)不回滚
    public void testDelete() throws Exception{
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.delete("/users/18");
        mvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk()).
                andExpect(MockMvcResultMatchers.content().string("SUCCESS"));
    }

    @Test
    public void testFindOne() throws Exception{
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/users/2");
        mvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk()).
                andExpect(MockMvcResultMatchers.content().
                        string("{\"id\":2,\"name\":\"xiaoming2\"}"));
    }

    @Test
    public void testUpdate() throws Exception{
        MockHttpServletRequestBuilder request = MockMvcRequestBuilders.put("/users");
        request.param("id","2");
        request.param("name","xiaoming222");
        mvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk()).
                andExpect(MockMvcResultMatchers.content().
                        string("{\"id\":2,\"name\":\"xiaoming222\"}"));
    }
}

最后,针对接口的测试,这里推荐一个好用的插件:Chrome浏览器的Postman,有兴趣的可以去了解一下。