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());
    }
}
 

猜你喜欢

转载自toplchx.iteye.com/blog/1537542