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

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    Java实现 蓝桥杯VIP 算法训练 数的统计
    Java实现 蓝桥杯VIP 算法训练 和为T
    Java实现 蓝桥杯VIP 算法训练 友好数
    Java实现 蓝桥杯VIP 算法训练 连续正整数的和
    Java实现 蓝桥杯VIP 算法训练 寂寞的数
    Java实现 蓝桥杯VIP 算法训练 学做菜
    Java实现 蓝桥杯VIP 算法训练 暗恋
    Java实现 蓝桥杯VIP 算法训练 暗恋
    测试鼠标是否在窗口内,以及测试鼠标是否在窗口停留
    RichEdit 各个版本介绍
  • 原文地址:https://www.cnblogs.com/javayida/p/13346799.html
Copyright © 2020-2023  润新知