如何测试使用MockMvc弹簧控制器的方法?(How to test a spring contro

2019-07-18 20:11发布

我使用弹簧3.2.0和JUnit 4

这是我需要测试我控制器的方法

@RequestMapping(value="Home")
public ModelAndView returnHome(){

return new ModelAndView("Home");    
}

弹簧servlet配置为:

<context:annotation-config/>
    <context:component-scan base-package="com.spring.poc" />
    <mvc:annotation-driven /> 

    <bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />

这是我的测试类:

public class TestController {

private MockMvc mockMvc;

@Before
public void setup() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/");
    viewResolver.setSuffix(".jsp");
    this.mockMvc = standaloneSetup(new CController()).setViewResolvers(
            viewResolver).build();
}

@Test
public void CControllerTest() throws Exception {
    ......
    ......      
}

}

如何测试这个方法与MockMvc?

Answer 1:

您可以使用以下annoations使用你的应用程序分发程序Servlet的XML。 下面的例子是打控制器,其与所述路径/ mysessiontest设置一些会话属性和期待一定视图要返回:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
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;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath:springDispatcher-servlet.xml" })

public class MySessionControllerTest {

    @Autowired WebApplicationContext wac; 
    @Autowired MockHttpSession session;
    @Autowired MockHttpServletRequest request;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void getAccount() throws Exception {
        UserDomain user = new UserDomain();
        user.setFirstName("johnny");

        session.setAttribute("sessionParm",user);
        this.mockMvc.perform(get("/mysessiontest").session(session)
        .accept(MediaType.TEXT_HTML))
        .andExpect(status().isOk())
        .andExpect(view().name("test"));
    }
}


文章来源: How to test a spring controller method by using MockMvc?