码迷,mamicode.com
首页 > 编程语言 > 详细

spring-mvc junit test

时间:2015-05-22 19:46:37      阅读:137      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!