SpringMVC 控制层的单元测试写法


IDEA快速创建单元测试

IDEA快速创建对应的单元测试:
选中类名—>idea快捷键—>ctrl+shift+t---->回车创建单元测试---->选中要测试的方法—>idea自动创建对应的包以及测试类

选中类名快捷键ctrl+shift+t
选中要测试的方法
自动创建测试方法

测试MVC

对MVC进行单元测试代码

@RunWith(SpringRunner.class)
//需要测试的Controller
@WebMvcTest(UserController.class)
public class UserControllerTest{

    @Autowired
    private MockMvc mvc;
    
    @MockBean
    UserService  uservice;

    @Test
    public void testMvc() throws Exception{
        int userId = 10;
        int expectCredit = 100;
                //模拟userService
        BDDMockito.given(this.userService.getCredit(userId)).willReturn(100);
                //MVC调用
        mvc.perform(MockMvcRequestBuilders.get("/user/{id}",userId))
            .andExpect(MockMvcResultMatchers.content().string(String.valueOf(expectCredit)));
    }
}
1. 测试Controller时使用@WebMvcTest注解,@WebMvcTest表示这是一个MVC测试,其参数可以传入多个待测试的Controller类,该注解不能和@SpringBootTest同时用,会报错。
2. MockMvc是Spring提供的专门用于测试SpringMVC类
3. @MockBean用来模拟实现,因为在SpringMVC测试中,Spring容器并不会初始化@Service注解的类(@WebMvcTest的缘故),因此我们需要模拟UserController调用的所有Service,这里就是Userservice,如果使用MockMvc对象时,又希望会加载所有被Spring容器管理的bean,可以使用@AutoConfigureMockMvc注解。
4. perform完成一次MVC调用,SpringMVC Test是Servlet容器内的一种模拟测试,实际上并不会发起一次真正的HTTP调用。
5. get方法模拟了一次Get请求,请求地址是/user/{id},这里的${id}会被后面的userId代替,因此请求地址是/user/10;
6. andExpect表示请求期望的返回结果,比如返回的内容或者HTTP响应头等

MVC测试的细节以及更多用法

模拟MVC请求

  1. 模拟Get请求:
mvc.perform(get("/users?name={name}","lisi"));
  1. 模拟Post请求:
mvc.perform(post("/users/{id}",42));
  1. 模拟文件上传:
mvc.perform(multipart("/doc").file("file","文件内容".getBytes("UTF-8")));
  1. 模拟请求参数:
    4.1 模拟提交message参数:
mvc.perform(get("/user/{id}/{name}",userId,name).param("message","hello"));相当于/user/userId/name?messag=hello

4.2 模拟一个checkbox提交:

mvc.perform(get("/user/{id}/{name}",userId,name).param("job","it","gov").param(...));

4.3 直接使用MultiValueMap构造参数:

LinkedMultiValueMap  params = new LinkedMultiValueMap (); 
params.put("message","hello");
params.put("job","it");
params.put("job","gov");
mcv.perform(get("/user/{id}/{name}",userId,name).param(params))
  1. 模拟Session和Cookie:
mvc.perform(get("/index.html").sessionAttr(name,value));mvc.perform(get("/index.html").cookie(new Cookie(name,value)));
  1. 设置HTTP Body的内容:
String json = "..."; mcv.perform(get("/index.html").content(json));
  1. 设置HTTP Header:
mcv.perform(get("/user/{id}/{name}",userId,name).contentType("application/x-www-form-urlencoded").accept("application/json").header(header1,value)

比较MVC的返回结果:

  1. 使用andExpect()可以添加期望返回的结果,以进行比较
mvc.perform(get("/user/1")).andExpect(status().isOk).andExpect(content().contentType(MediaType.APPLICATION_JSON));
  1. 校验ModelAndView:
mvc.perform(get("/user/1")).andExpect(view().name("success.btl"));
  1. 检验Model:
mvc.perform(get("/user/1")).andExpect(model().attributeExists("persion"));
  1. 比较forward或者redirect:
mvc.perform(get("/user/1")).andExpect(forwardeUrl("index.html"));
  1. 比较返回内容:
mvc.perform(get("/user/1")).andExpect(content().string("Hello World"));

猜你喜欢

转载自blog.csdn.net/qq_38371367/article/details/102758131