spring-mvc junit test

在spring-mvc中测试controller层,一般比较麻烦,因为没有web容器中的那种上下文环境,而启动容器测试又不够优雅。

maven依赖,其中需要注意的是用到了spring-test-mvc,这么一个框架。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.2.13.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.13.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.13.RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test-mvc</artifactId>
    <version>1.0.0.M1</version>
    <scope>test</scope>
</dependency>


和普通的spring测试稍有不同的是多了一个注解@WebAppConfiguration, 其中用到了模拟对象MockMvc,这是spring-test-mvc框架中的东西,java 代码如下:

package com.spring.demo.web.controller;

import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;

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.server.MockMvc;
import org.springframework.test.web.server.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.spring.demo.init.AppConfig;
import com.spring.demo.init.web.MvcConfig;

/**
 * 使用模拟对象测试controller
 * 
 * @author sean
 * 
 */
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, MvcConfig.class })
public class PingControllerTest {

    @Autowired
    private WebApplicationContext applicationContext;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders
                .webApplicationContextSetup(applicationContext).build();
    }

    @Test
    public void test() throws Exception {
        assertNotNull(mockMvc);
        mockMvc.perform(get("/ping/show")).andExpect(status().isOk())
                .andExpect(forwardedUrl("/WEB-INF/pages/ping/show.jsp"));

    }
}


具体项目,请参考springDemo

你可能感兴趣的:(spring-mvc junit test)