使用Cobertura生成测试覆盖率报告
前言:本文章需要JUnit单元测试框架的基础知识,若读者还不具备,请阅读笔者的JUnit文章:http://ray-yui.iteye.com/blog/1914106
UnitTest系列文章:
使用JUnit开发单元测试:http://ray-yui.iteye.com/blog/1914106
使用DBUnit扩展JUnit:http://ray-yui.iteye.com/blog/1914979
使用EasyMock扩展Junithttp://ray-yui.iteye.com/blog/1916170
使用Cactus测试Servlethttp://ray-yui.iteye.com/blog/1917515
使用Spring TestContext测试Spring应用http://ray-yui.iteye.com/blog/1921424
什么是测试覆盖率?
覆盖率是测量测试完整性的一个手段,是衡量测试是否完整的一个标准,我们编写的代码当中每个分支都应该是被覆盖的,这样才能保证测试是完全的,正确的.请留意以下例子
package com.accentrix.ray.service;import com.accentrix.ray.dao.UserDao;import com.accentrix.ray.entity.User;public class UserService {UserDao userDao = new UserDao();public User login(String username, String password) {User user = userDao.get(username);if (user == null)throw new RuntimeException("用户名不存在");if (user.getPassword().equals(password))throw new RuntimeException("密码错误");return user;}}
package com.accentrix.ray.test;import junit.framework.Assert;import org.junit.Before;import org.junit.Test;import com.accentrix.ray.entity.User;import com.accentrix.ray.service.UserService;public class TestUserService {private User user;private UserService userService;@Beforepublic void setUp() {user = new User(1, "Ray", "123");userService = new UserService();}@Test(expected = RuntimeException.class)public void testUsernameNotExistLogin() {// 测试用户名不存在的情况userService.login("test", "123");}@Test(expected = RuntimeException.class)public void testPasswordNotMatchLogin() {// 测试密码不正确的情况userService.login(user.getUsername(), "4444");}@Testpublic void testAccessLogin() {//测试成功登陆User loginUser = userService.login(user.getUsername(),user.getPassword());Assert.assertNotNull(loginUser);Assert.assertEquals(loginUser.getUsername(), user.getUsername());Assert.assertEquals(loginUser.getPassword(), user.getPassword());}}
<plugin><groupId>org.codehaus.mojo</groupId><artifactId>cobertura-maven-plugin</artifactId><version>2.4</version></plugin>