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

转载于:https://my.oschina.net/u/2007041/blog/418748

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值