October 27, 2024
Chicago 12, Melborne City, USA
java

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.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video