zoukankan      html  css  js  c++  java
  • 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().
    在这里插入图片描述
    在这里插入图片描述

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    日常排雷:redis报错 could not get a resource from the pool
    阿里云centos服务器tomcat启动后,浏览器请求无响应
    并发生产顺序单据号测试
    json 数据 格式,请求接口,部分字段无法注入
    baomidou 动态数据源@DS 使用问题
    SpringMVC框架深入(八)--SpringMVC原理
    Spring框架深入(七)--json数据交互
    框架理论深入(六)--拦截器
    Spring框架深入(五)--文件上传和异常处理
    int和Integer的区别
  • 原文地址:https://www.cnblogs.com/javayida/p/13346799.html
Copyright © 2011-2022 走看看