controller层的单元测试

Base的测试类,其他所有测试类继承这个类:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试
@ContextConfiguration(locations = {"classpath:springmvc.xml","classpath:conf/spring/spring-mybatis.xml", "classpath:test/spring.xml"})
@WebAppConfiguration
public class BaseUnit {

    protected MockMvc mockMvc;

    @Autowired
    protected WebApplicationContext wac;

    @Before()
    public void setup()    {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc对象
    }

    @Before
    public void before() {
    }

    @Test
    public void test() throws Exception {
    }

}

主测试类里面引入springmvc的配置,同时需要加上注解@WebAppConfiguration,
然后单侧里面使用mockMvc模拟请求即可:


@Slf4j
public class TestControllerTest extends BaseUnit {

    private String uri = "/test";

    @Test
    public void test1() throws Exception {
        ResultActions resultActions = this.mockMvc
                .perform(MockMvcRequestBuilders.post(uri + "/test1")
                        .param("ip", "192.168.1.1")
                        .param("user", "aaa")
                        .param("password", "bbb")   
                        .accept(MediaType.APPLICATION_JSON_VALUE));
        MvcResult mvcResult = resultActions.andReturn();
        String result = mvcResult.getResponse().getContentAsString();
        log.error("返回的数据:" + result);
    }
   }

这边修改请求的方法类型:get请求就get,put就put.参数的话,如果是json的话,就.content().
在这里插入图片描述
在这里插入图片描述

世界上所有的不公平都是由于当事人能力不足造成的.
原文地址:https://www.cnblogs.com/javayida/p/13346799.html