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().
    在这里插入图片描述
    在这里插入图片描述

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    eclipse maven Errors while generating javadoc on java8
    log4j升级到logback
    httpclient新旧版本分割点4.3
    javadoc中{@link}与@see的简单使用以及区别
    maven-shade-plugin插件
    jar中META-INF
    dubbo环境搭建与tomcat集成、DEMO示例、常见问题(最完整版本、带管理控制台、监控中心、zookeeper)
    叶亚明:合格CTO的六要素(转)
    rocketmq安装与基本操作
    当我们在谈论技术时,技术的本质和价值究竟是什么?
  • 原文地址:https://www.cnblogs.com/javayida/p/13346799.html
Copyright © 2011-2022 走看看