javaeclipseunit-testingtestingjunit

JUnit4 code coverage issue with Exception expected


I have the following sample class in Java:

package main;

public class SampleClass {
    private String id;

    public SampleClass(String id) throws IllegalArgumentException {
        validation(id);
        this.id = id;
    }

    public void validation(String inputId) throws IllegalArgumentException {
        if (inputId.length() != 6) {
            throw new IllegalArgumentException("Invalid length");
        }
    }
}

And now, I'm trying to test the code with JUnit4 tests like the following:

package main;

import org.junit.rules.ExpectedException;

public class Test {

    @org.junit.Rule
    public ExpectedException thrown = ExpectedException.none();

    @org.junit.Test
    public void normalTest() {
        SampleClass sample = new SampleClass("123456");
    }

    @org.junit.Test(expected = IllegalArgumentException.class)
    public void lengthTestOriginal() {
        SampleClass sample = new SampleClass("1234567");
    }

    @org.junit.Test
    public void lengthTestVersion1() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("Invalid length");
        SampleClass sample = new SampleClass("12345");
    }

    @org.junit.Test
    public void lengthTestVersion2() {
        try {
            SampleClass puerto2 = new SampleClass("1234567");
        } catch (IllegalArgumentException e) {
            org.junit.Assert.assertEquals("Invalid length", e.getMessage());
        }
    }
}

However, when I run the JUnit tests with coverage, the SampleClass() instantiations that must throw an exception seem to not being covered, as shown in the image: enter image description here

I know the tool may not be able to detect such code as covered, as discussed here, however, is the any way to write the tests so that they show as covered? As you can see I tried several alternative ways to perform the same test, all of them failing to be covered in the same instantiation line.


Solution

  • You show the coverage of the test class, not the coverage of the class under test, which is 100%. If you want your test case classes to have 100% coverage, you must write test cases for your test cases, and there's no end to that. But be my guest ;)