spring3 mvc 单元测试

/*
 * 文件名:TestMVC.java
 * 版权:Copyright 2012-2012 Li Huaxin Tech. Co. Ltd. All Rights Reserved. 
 * 描述: TestMVC.java
 * 修改人:lihuaxin
 * 修改时间:2012-8-28
 * 修改内容:新增
 */
package com.huaxin.unit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;

/**
 * Spring mvc 单元测试
 * 
 * @author lihuaxin
 * @version LMS V100R001 2012-8-28
 * @since LMS V100R001C00
 */
@ContextConfiguration(locations = {"/applicationContext.xml","file:WebContent/WEB-INF/springmvc-servlet.xml"})
public class TestMVC extends AbstractJUnit4SpringContextTests
{
    @Autowired
    private DefaultAnnotationHandlerMapping handlerMapping;

    @Autowired
    private AnnotationMethodHandlerAdapter handlerAdapter;

    /**
     * 
     * 执行请求
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView excuteAction(HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
        HandlerExecutionChain chain = handlerMapping.getHandler(request);
        final ModelAndView model = handlerAdapter.handle(request, response,
                chain.getHandler());
        return model;
    }
    
    @Test
    public void testRequest()
    {
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        request.setRequestURI("/role/list");
        request.setMethod("GET");
        // 执行URI对应的action
        try
        {
            final ModelAndView mav = this.excuteAction(request, response);
            // 执行结果
            System.out.println(mav.getViewName());
            Object msg = mav.getModelMap().get("roles");
            System.out.println(" = " + msg);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值