SpringMVC : Controller层单元测试Mock

代码

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:applicationContext.xml",
		"file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml" })
public class MvcTest {
	 
	@Autowired
	WebApplicationContext context;
	 
	MockMvc mockMvc;

	@Before
	public void initMokcMvc() {
		mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}

	@Test
	public void testPage() throws Exception {
		 
		MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/messages").param("pn", "5"))
				.andReturn();
		 
		MockHttpServletRequest request = result.getRequest();
		PageInfo pi = (PageInfo) request.getAttribute("pageInfo");
		System.out.println(pi);		
	}

}

配置测试环境

  1. pom.xml中导入 Spring test 模块
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    
  2. 注意 : Spring4 测试的时候,需要 servlet3.0的支持
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>        
    
  3. 给测试类配置注解
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(locations = { "classpath:applicationContext.xml",
            "file:src/main/webapp/WEB-INF/dispatcherServet-servlet.xml" })  
    
    1. @RunWith(SpringJUnit4ClassRunner.class) 测试运行于Spring测试环境;
    2. @ContextConfiguration 加载Spring的配置文件
    3. @WebAppConfiguration 表明应该为测试加载WebApplicationContext,必须与@ContextConfiguration一起使用
    4. @Before 编写测试方法执行前的逻辑,可以初始化MockMVC实例
    5. @Test 标明实际测试方法,建议每个Controller对应一个测试类。

在测试类中,编写测试逻辑

调用 mockMvc.perform 执行模拟请求

  1. 代码来源
    MockHttpServletRequestBuilder createMessage = 
        get("/messages").param("pn", "5");
    
    mockMvc.perform(createMessage)
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl("/messages/123"));
    
    1. get请求和Controller中的方法请求类型对应
    2. param为传递的参数,允许多个
    3. andExpect为结果断言,
    4. isOk代表的是返回正常也就是http的200,
    5. view.name为返回的视图名称
    6. andDo为执行后操作,本例的print为打印出结果
    7. return返回结果,可以对结果进一步操作

关键词

springMVC整合Junit4进行单元测试Spring中DAO层接口的单元测试

猜你喜欢

转载自blog.csdn.net/ai_shuyingzhixia/article/details/82828226