欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc单元测试

程序员文章站 2022-04-29 16:45:07
...

作为WEB开发人员在开发过程中总是需要测试各种请求
常规的方法则是启动WEB服务器 测试 出错 停掉WEB 改代码 重启WEB 测试
大量的时间都浪费在WEB服务器的启动上
今天给大家介绍一种不用启动WEB 直接采用单元测试的方法来测试请求是否准确
该方法基于SpringMVC 与 spring Test 框架
如果大家对SpringMVC的基本知识不了解,请先百度一下.

直接上代码

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

import java.net.URI;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;  

@RunWith(SpringJUnit4ClassRunner.class)  
@WebAppConfiguration  
@ContextConfiguration(locations = {"classpath:spring-context.xml","classpath:spring-mvc.xml","classpath:spring-context-shiro.xml","classpath:spring-context-jedis.xml","classpath:spring-context-activiti.xml"})  
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否  
@TransactionConfiguration(defaultRollback = true)  
//记得要在XML文件中声明事务哦~~~我是采用注解的方式  
@Transactional  
public class ExampleTests {  

    @Autowired  
    private WebApplicationContext wac;  

    private MockMvc mockMvc;  

    @Before  
    public void setup() {  
        // webAppContextSetup 注意上面的static import  
        // webAppContextSetup 构造的WEB容器可以添加fileter 但是不能添加listenCLASS  
        /* WebApplicationContext context =  
         ContextLoader.getCurrentWebApplicationContext();  */
        // 如果控制器包含如上方法 则会报空指针  
       // this.mockMvc = webAppContextSetup(wac).build();  
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    }  

    @Test  
     //有些单元测试你不希望回滚  
     @Rollback(false)  
    public void ownerId() throws Exception {  
        URI uri = new URI("/app/spring/rest");
        MockHttpServletRequestBuilder b = get(uri);
        //MockHttpServletRequestBuilder b =     MockMvcRequestBuilders.post(uri);
        mockMvc.perform(b)
                .andDo(print());  
    }  

//    @Test  
//    public void test() throws Exception {  
//        mockMvc.perform((get("/spring/test"))).andExpect(status().isOk())  
//                .andDo(print())  
//                .andExpect(model().attributeHasNoErrors("teacher"));  
//    }  
//  
//    @Test  
//    public void testb() throws Exception {  
//        mockMvc.perform((get("/spring/testb"))).andExpect(status().isOk())  
//                .andDo(print());  
//    }  
//  
//    @Test  
//    public void getAccount() throws Exception {  
//        mockMvc.perform((post("/spring/post").param("abc", "def")))  
//                .andExpect(status().isOk()).andDo(print());  
//    }  
//  
}

下面是坑

当出现以下问题时请不要慌

MockHttpServletRequest:
         HTTP Method = GET
         Request URI = /app/spring/rest
          Parameters = {}
             Headers = {}

             Handler:
                Type = null

               Async:
   Was async started = false
        Async result = null

  Resolved Exception:
                Type = null

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 404
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

或出现这个

java.lang.AssertionError: Status expected:<200> but was:<404>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:549)
    ...

这是因为DispatcherServlet里边找不到对应的名字就是接口(/app/spring/rest)
找不到对应的类了,注意@ContextConfiguration里边是否加载了annotation扫描

maven中配置

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.8.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.8.4</version>
            <scope>test</scope>
        </dependency>

…明明有很多问题的。。。写的时候居然想不起来了。算了想起来再说吧。