【Spring Boot 单元测试】3. 使用Mock单元测试Controller

眉间皱痕 提交于 2020-01-07 01:23:41

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

如下简单Controller:

@RestController
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("user/{userName}")
    public Map<String,String> getUserByName(@PathVariable(value = "userName") String userName) {
        return this.userService.findByName(userName);
    }

    @PostMapping("user/save")
    public void saveUser(@RequestBody User user) {
        //添加成功
        System.out.println("添加成功:"+user.getName());
    }

}

 

现在编写一个针对于该ControllergetUserByName(@PathVariable(value = "userName") String userName)方法的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    /**
     * 测试方法开始之前执行   设置模拟Mvc
     */
    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }



    @Test
    public void test() throws Exception {
        mockMvc.perform(
                MockMvcRequestBuilders.get("/user/{userName}","admin").
                contentType("application/json"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("admin"))
                .andDo(MockMvcResultHandlers.print());
    }

}

运行后,JUnit通过,控制台输出过程如下所示:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /user/admin
       Parameters = {}
          Headers = [Content-Type:"application/json"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.restful.springrestfuldemo.controller.UserController
           Method = com.restful.springrestfuldemo.controller.UserController#getUserByName(String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"name":"admin","id":"1"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

 

继续编写一个针对于该ControllersaveUser(@RequestBody User user)方法的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    ObjectMapper mapper;

    /**
     * 测试方法开始之前执行   设置模拟Mvc
     */
    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }



    @Test
    public void test() throws Exception {
        User user = new User();
        user.setName("admin");
        user.setPwd("123456");

        String userJson = mapper.writeValueAsString(user);
        mockMvc.perform(
                MockMvcRequestBuilders.post("/user/save")
                        .contentType("application/json")
                        .content(userJson.getBytes()))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print());
    }

}

运行过程如下所示:

添加成功:admin

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /user/save
       Parameters = {}
          Headers = [Content-Type:"application/json", Content-Length:"31"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.restful.springrestfuldemo.controller.UserController
           Method = com.restful.springrestfuldemo.controller.UserController#saveUser(User)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

值得注意的是,在一个完整的系统中编写测试单元时,可能需要模拟一个登录用户信息Session,MockMvc也提供了解决方案,可在初始化的时候模拟一个HttpSession:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    ObjectMapper mapper;

    private MockHttpSession session;

    /**
     * 测试方法开始之前执行   设置模拟Mvc
     */
    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
        session = new MockHttpSession();
        User user =new User();
        user.setName("admin");
        user.setPwd("123456789");
        session.setAttribute("user", user);
    }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!