SpringBoot系列(4)---SpringMVC测试用例

本文介绍了如何在SpringBoot项目中使用SpringMVC进行测试,包括添加Spring-test依赖和编写测试类。通过示例展示了MockMvcResultHandlers.print()方法打印的详细信息,强调了编写测试用例的重要性,尤其是在时间允许的情况下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

虽然SpringMVC的测试用例我也没有怎么用,但是以防以后我会用到还是写一些笔记比较好。

使用SpringMVC的测试,需要添加Spring-test MAVEN依赖如下:

Spring-test:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
</dependency>
Junit4:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

直接上测试类,注释写得非常详细,基本上平时用到的测试都在这里了。认真看看就明白了~ 但是老实说,我真的非常少用。笔者所在的团队一共差不多20人,25个工作日的事件开发一个商城APP,事件要求非常紧。通常一个mac上的paw测测接口就OK了,真的没有这么花事件去写测试用例。但是事实上时间允许的前提下,还是写一下测试用例比较好。而且在andDo(MockMvcResultHandlers.print())方法打印出来的信息真的非常全和整洁,一出问题可以马上发现,比日志信息还好看。所以还是建议写一下的····

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfig.class})
@WebAppConfiguration("src/main/resources")
public class TestControllerIntegration {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext ctx;

    @Autowired
    MockHttpSession session;

    @Autowired
    MockHttpServletRequest request;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build();
    }

    @Test
    public void testNormalController() throws Exception {
        //访问/index 添加断言 http状态是否200 返回的视图是否为/index
        mockMvc.perform(MockMvcRequestBuilders.get("/index"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.view().name("/index"));
    }

    @Test
    public void testJson() throws Exception {
        //访问/loginAction登录接口,然后添加两个参数 用户名和密码, andDo 打印整个请求和影响的所有信息
        //返回一个result,注意我们在最后添加andReturn方法,返回一个MvcResult 在这个Result获得一个session
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/loginAction").
                param("username", "tony").
                param("password", "tonypwd"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.view().name("main"))
                .andDo(MockMvcResultHandlers.print()).andReturn();

        this.session = (MockHttpSession) result.getRequest().getSession();

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

        
        //使用之前的session 获得当前登录用户的Json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType("application","json"));
        result = mockMvc.perform(MockMvcRequestBuilders.post("/userInfo.json")
                        .headers(headers).session(this.session))
                        .andExpect(MockMvcResultMatchers.status().isOk())
                        .andDo(MockMvcResultHandlers.print()).andReturn();
        System.out.println(result.getRequest().getSession().getAttribute("loginUser"));
    }

}

看到这里你会说andDo(MockMvcResultHandlers.print())打印出来的信息有多详细啊··· 呵呵 我准备好了给你们看看我的控制台(真的非常详细):


MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /loginAction
       Parameters = {username=[tony], password=[tonypwd]}
          Headers = {}


Handler:
             Type = com.tony.controller.IndexController
           Method = public org.springframework.web.servlet.ModelAndView com.tony.controller.IndexController.loginAction(javax.servlet.http.HttpSession,java.lang.String,java.lang.String,java.lang.String)


Async:
    Async started = false
     Async result = null


Resolved Exception:
             Type = null


ModelAndView:
        View name = main
             View = null
        Attribute = msg
            value = other message from GlobalHandlerAdvice !!!
        Attribute = username
            value = tony
        Attribute = loginMsg
            value = 登录成功


FlashMap:
       Attributes = null


MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = /WEB-INF/views/main.jsp
   Redirected URL = null
          Cookies = []
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /userInfo.json
       Parameters = {}
          Headers = {Content-Type=[application/json]}


Handler:
             Type = com.tony.controller.IndexController
           Method = public com.tony.entity.User com.tony.controller.IndexController.getUserInfo(javax.servlet.http.HttpSession)


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;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"username":"tony","userpwd":"tonypwd"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
User{username='tony', userpwd='tonypwd'}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值