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

springMvc controller 单元测试

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

springMvc 3.1.2版本 controller 单元测试

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/WEB-INF/monitor-servlet.xml",   "classpath:/spring/spring-core.xml"})
public class JobControllerTest {
    @Autowired
    public RequestMappingHandlerAdapter handlerAdapter;
    @Autowired
    private JobController jobController;

    private static MockHttpServletRequest request;

    private static MockHttpServletResponse response;

    @BeforeClass
    public static void before() {
        request = new MockHttpServletRequest();
        request.setCharacterEncoding("UTF-8");
        response = new MockHttpServletResponse();
    }

    @Test
    public void testList() {
        request.setRequestURI("/job/list");
        request.setMethod(HttpMethod.POST.name());
        ModelAndView mv = null;
        try {
            mv = handlerAdapter.handle(request, response, new     HandlerMethod(jobController, "list"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Assert.assertNotNull(mv);
        Assert.assertEquals(response.getStatus(), 200);
        Assert.assertEquals(mv.getViewName(), "/job/job_list");
    }
}

转载于:https://my.oschina.net/u/569410/blog/89764