Cobertura is a powerful tool to increase test coverage of Java software. It reports and checks your test coverage. At this Cobertura analyzes the called logic by tracing tests and business logic classes. For example based on branch and line rates you can abort the build. Furthermore the offered Cobertura Maven Plugin can be used directly at development process. The following requirements and example describes how to work basically with Cobertura.
(1). For reporting. Command is "mvn cobertura:cobertura". It generates a coverage report at target/site/cobertura:(2). Define rates. If rates will be exceeded the build will fail:org.codehaus.mojo cobertura-maven-plugin
(3). Test and business logic classes: --- Beansorg.codehaus.mojo cobertura-maven-plugin 85 85 true 85 85 85 85 clean check
public class User {
private String foreName;
public String getForeName() {
return foreName;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
private String surName;
public String geSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
--- Logic
public class RegistrationService
{
private void sendEmail(User user) {
//some code
}
private void sendSms(User user) {
//some code
}
public void registerUser(User user) {
if (user.getEmail().endsWith(".com")) {
sendSms(user);
} else {
sendEmail(user);
}
}
}
--- Test
public class RegistrationServiceTest {
@Test
public void testRegistration() {
//empty
}
}
Your test is empty. That's why the build aborts. The following report shows you the coverage lacks.
(4.) Now you add testing coding.
import org.junit.Test;
public class RegistrationServiceTest {
@Test
public void testRegistration() {
RegistrationService regService =
new RegistrationService();
//test else clause
User deUser = new User();
deUser.setForeName("Rafael");
deUser.setSurName("Sobek");
deUser.setEmail("rafael@debelopers-blog.org");
regService.registerUser(deUser);
//test {if (user.getEmail().endsWith(".com"))) ...}
User comUser = new User();
deUser.setForeName("Rafael");
deUser.setSurName("Sobek");
deUser.setEmail("rafael@googlemail.com");
regService.registerUser(deUser);
}
}
Now 88 percent of your code are coveraged. Look at the following pictures. First shows a summary and the last images shows you a detail look to the coverage of your classes.



Regards
Rafael Sobek
Technorati Tags: Test Coverage Cobertura
