Search code examples
javajunitcode-coverageeclemma

Why is code coverage measured in test cases?


I have measured code coverage using EclEmma. I would have expected that only source packages are under test. Surprisingly JUnit Test Cases are also measured.

public class EmailTest {

public static final String VALID_MAIL = "[email protected]";

public static final String INVALID_MAIL_WITHOUT_AT = "xyzqwe.abc";

@Test
public void shouldCreateValidEmail() {
    Email email = null;
    try {
        email = new Email (VALID_MAIL);
    } catch (NotValidEmailException e) {
        Assert.fail();
    }
    Assert.assertEquals("Email: " + VALID_MAIL + " should be correct created", VALID_MAIL, email.getEmail());
}

@Test(expected = NotValidEmailException.class)
public void shouldThrowExceptionWhenMailHasNoAt() throws NotValidEmailException {
    new Email (INVALID_MAIL_WITHOUT_AT);
}

Just for example I have a basic Test Case for Email-Regex Validation. Test Coverage for this test class "EmailTest" is 73%. The Class under test "Email" is in 100% covered.

Why is code coverage in test cases measured and what is that for?


Solution

  • You can exclude test code from coverage, but you shouldn't. Coverage is designed to tell you important things about your code. Your test code is also important. For example, you may have code in your test helpers that is never run: you can delete that code. Or you may have accidentally written test lines that are never executed for some reason.

    The only reason to exclude test code is if you have set yourself some arbitrary goal like 75% coverage, and don't want to "cheat" by including your tests. There is no meaning to those goals, so don't let them limit what you find out from coverage.