首页 > 编程语言 > 详细

spring-mvc junit test

时间:2015-05-22 19:44:59      阅读:254      评论:0      收藏:0      [点我收藏+]

在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

原文:http://my.oschina.net/u/2007041/blog/418748

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!