05 February 2017
Java code coverage
In Java there are a wide variety of code coverage tools out there. One of the most popular is jacoco which provides an easy setup if you're using maven or gradle. This post will be showing how to setup a java project in maven using jacoco code coverage.
1. Maven dependency
Insert maven dependency for jacoco in your maven project:
2. Maven plugin
Insert maven plugin for jacoco in your maven project:
3. Sample Unit test
public class User {
private String name;
public User(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isValid() {
return (name != null && !name.equals("") && name.length() <= 10);
}
}
Unit test:
import org.junit.Assert; import org.junit.Test;
public class UserTest { / * Tests set and get */ @Test public void testUserGettersAndSetters() { User user = new User("joe"); user.setName(""); Assert.assertTrue(user.getName().equals("")); user.setName(null); Assert.assertTrue(user.getName() == null); user.setName("java"); Assert.assertTrue(user.getName().equals("java")); } @Test public void testUserIsValid() { User user = new User("joe smith"); Assert.assertTrue(user.isValid()); } / * Tests user name null / @Test public void testUserNameNull() { User user = new User(null); Assert.assertTrue(!user.isValid()); } /** * Tests user name empty / @Test public void testUserNameEmpty() { User user = new User(""); Assert.assertTrue(!user.isValid()); } /* * Tests user name too Long / @Test public void testUserInavlidNameTooLong() { User user = new User("joe the world wide clock field service man"); Assert.assertTrue(!user.isValid()); } }
4. Run maven build and see test coverage report
run mvn clean install or mvn test to trigger the unit test execution. Once tests are finished check file {PROJECT_FOLDER}/target/site/jacoco/index.html for coverage report (open in any browser):