`
toplchx
  • 浏览: 339248 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring MVC的单元测试

阅读更多

功能代码按照Spring的标准书写,无论是通过XML配置还是通过annotation配置都可以。

 

测试代码最重要的是告诉framework去哪里找bean的配置。

 

以Dao的Test为例:

 

 

//告诉framework怎么运行这个类
@RunWith(SpringJUnit4ClassRunner.class) 
//bean的配置文件路径,这个是Test类的classpath路径,如果是Spring推荐的目录结构,应该在:项目目录/src/test/resources/里
@ContextConfiguration(locations = "classpath:app-config.xml")  
public class TestPatchDao extends AbstractTransactionalJUnit4SpringContextTests {
    //取得要测试的Dao类
    @Resource
    private PatchDao patchDao;

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    /**
     * 测试方法
     */
    @Test
    public void testGetPatchList_1() {
        //Dao的某个方法
        List<Map<String, Object>> list = patchDao.getPatchList(1, "00C8002D00000000", 1);
        assertEquals(1, list.size());
    }
}
 

 

再举一个Controller的例子

 

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:app-config.xml", "classpath:mvc-config.xml"})
public class TestMainCtrl extends AbstractTransactionalJUnit4SpringContextTests {
    @Autowired
    private MainCtrl controller;

    //这种方法适用于Springframework3.0,3.1换了handler的处理类。
    @Autowired
    private AnnotationMethodHandlerAdapter handlerAdapter;

    private final MockHttpServletRequest request = new MockHttpServletRequest();
    private final MockHttpServletResponse response = new MockHttpServletResponse();

    @Test
    public void testMain4User() throws Exception {
        request.setRequestURI("/main");
        request.setMethod(HttpMethod.POST.name());
        HttpSession session = request.getSession();
        //设置 认证信息
        session.setAttribute(CommonConstants.SESSION_USER_TYPE, 1);
        session.setAttribute(CommonConstants.SESSION_USER_ID, 0);
        session.setAttribute(CommonConstants.SESSION_USER_ACC, "aa1");

        ModelAndView mav = handlerAdapter.handle(request, response, controller);
        assertEquals("/regist", mav.getViewName());
    }
}
 

TestSuite的写法,将Test类用注解的方式配置到TestSuite类上。

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses( { TestPatchDao.class, TestMainCtrl.class })
public class TestSuite {}
 


统计覆盖率。单元测试的标准往往是代码附带率,发现比较好的工具是CodePro Analytix,它是google收购的一个项目,项目主页:https://developers.google.com/java-dev-tools/codepro/doc/
这个工具的功能都很实用,它还可以自动生成测试代码。测试代码以独立的项目存在,可以根据功能代码的流程分支生成的测试方法,比如功能代码里有一个if else,测试代码就会生成3个测试方法,以便每个分支都能覆盖到。
我们主要使用它的代码覆盖率功能,这个工具不但可以统计测试时的代码覆盖率,还可以统计debug时的覆盖率。
1、按照安装说明,将工具安装进Eclipse
2、右键点击项目,选择CodePro Tools --> Instrument for Code Coverage。
再运行测试类或debug,都会出覆盖率的统计。

但是统计覆盖率会降低代码运行效率,所以,不需要统计时再 Unistrument 就可以了。

---------------------------------------------

Springframework3.1和springsecure的controller测试类例子:


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:root-context.xml", 
		"classpath:servlet-context.xml", "classpath:security-app-context.xml"})
public class TestSecureCtrl extends AbstractTransactionalJUnit4SpringContextTests {
    @Autowired
    private SecureCtrl controller;
    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    private final MockHttpServletRequest request = new MockHttpServletRequest();
    private final MockHttpServletResponse response = new MockHttpServletResponse();
	
    @Test
    public void testMain4User() throws Exception {
        request.setRequestURI("/secure");
        request.setMethod(HttpMethod.POST.name());
        HttpSession session = request.getSession();
	    
        //设置springsecure的内容
        List<GrantedAuthority> ga = new ArrayList<GrantedAuthority>();
        ga.add(new GrantedAuthorityImpl("ROLE_ALL"));
        User user = new User("account", "password", true, true, true, true, ga);
        SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(user, null));
        session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());

        ModelAndView mav = handlerAdapter.handle(request, response, new HandlerMethod(controller, "home", Model.class, HttpServletRequest.class));

        assertEquals("home", mav.getViewName());
    }
}
 
分享到:
评论
1 楼 scaler08 2014-08-13  
[/flash][/flash][/flash][/flash][/fla
sh][/flash][/flash][img][url][url][img][list]
[*][img]
[u]
引用
[/u]
[/img]
[/list][/img][/url][/url][/img]

相关推荐

    spring mvc的简单单元测试

    spring mvc的简单单元测试:,详细请参考:http://blog.csdn.net/xiejx618/article/details/21201007

    精通Spring MVC 4

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    spring mvc jpa单元测试例子

    这是一个测试事务管理的例子,希望对你们有所帮助,项目里子是在myeclipse中的maven创建的。myeclipse应该可以直接运行。

    Spring MVC入门教程

    十三、如何给spring3 MVC中的Action做JUnit单元测试? 十四、spring mvc 转发与重定向 十五、spring mvc 处理ajax请求 十六、spring mvc 关于写几个配置文件的说明 十七、spring mvc 如何取得Spring管理的bean 十八...

    Spring MVC 教程 快速入门 深入分析

    十三、如何给spring3 MVC中的Action做JUnit单元测试? 十四、spring mvc 转发与重定向 十五、spring mvc 处理ajax请求 十六、spring mvc 关于写几个配置文件的说明 十七、spring mvc 如何取得Spring管理的bean 十八...

    spring MVC junit 单元测试(controller)

    NULL 博文链接:https://zkf60553.iteye.com/blog/1604723

    Spring Boot中的单元测试.pdf

    Spring Boot中的单元测试.pdfSpring Boot中的单元测试.pdfSpring Boot中的单元测试.pdfSpring Boot中的单元测试.pdfSpring Boot中的单元测试.pdfSpring Boot中的单元测试.pdfSpring Boot中的单元测试.pdfSpring Boot...

    SpringMVC框架架构介绍

    十三、如何给spring3 MVC中的Action做JUnit单元测试? 十四、spring mvc 转发与重定向 十五、spring mvc 处理ajax请求 十六、spring mvc 关于写几个配置文件的说明 十七、spring mvc 如何取得Spring管理的bean ...

    单元测试案例junit +spring mvc +springboot

    单元测试案例junit +spring mvc +springboot

    test-mvc:使用 Spring MVC 测试框架进行测试

    该项目的目标是证明: 如何使用 DispatcherServlet 为控制器编写单元测试来处理请求,从而在不需要运行 Servlet 容器的情况下近似完整的集成测试; 如何编写集成测试来测试所有应用程序层的集成,而无需运行 ...

    精通Spring MVC 4 [精校高清版](Geoffroy.Warin). pdf

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    Spring+spring MVC+MyBatis示例

    Spring+spring MVC+MyBatis示例程序,maven构建,程序演示了增、删、改、查、分页、单元测试等有代表性的操作,可供初学者借鉴。

    spring mvc框架demo

    spring mvc框架搭建demo,同时支持junit单元测试的实例demo。

    精通spring mvc 4

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    精通SpringMVC(高清目录版含源码实例)

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    Ant+Junit+Svn实现自动单元测试

    Ant+Junit+Svn实现自动单元测试

    spring4.0 mvc api

    spring4.0 mvc api 单元测试 文件上传 ,文件下载

    spring mvc后台管理系统

    session-data-redis解决分布式统一session管理,也有junit4单元测试,前端jQuery、bootstrap、以及其他很多流行的js组件。目前已经完整整合,即可做为restapi也可作为前端展示,一般的业务可以基于此快速开发,大幅...

Global site tag (gtag.js) - Google Analytics