Testing for same exception using multiple parameters under same test method in JUnit 4

doctopus :

I have a method that checks for null arguments, and throws an IllegalStateException if any are null:

public V put(K key, V value)
{
    if (key == null || value == null) {
        throw new IllegalStateException();
    }
.....
}

In JUnit4 I've been creating three separate test methods to cover all the possibilities: put(key, null), put(null, value) and put(null, null):

@Test(expected = IllegalStateException.class)
public void testPutThrowsIllegalStateException1() {
    llmm.put("A", null);
}

@Test(expected = IllegalStateException.class)
public void testPutThrowsIllegalStateException2() {
    llmm.put(null, 1);
}

@Test(expected = IllegalStateException.class)
public void testPutThrowsIllegalStateException3() {
    llmm.put(null, null);
}

It works as intended, but the problem is that it's rather tedious and verbose. If I try to group them under one method like so, then Eclipse tells me I'm missing some coverage:

@Test(expected = IllegalStateException.class)
public void testPutThrowsIllegalStateException1() {
    llmm.put("A", null);
    llmm.put(null, 1);
    llmm.put(null, null);

Is there a quicker way where I can group all 3 into 1 test method?

JB Nizet :

Your unique test fails as soon as its first line is executed, and the other two are thus never executed.

Having 3 (or just 2) tests is fine.

Another way is to avoid using the expected attribute, and instead use a good assertions library (or create such an assertion yourself).

For example, using AssertJ, you could write your test that way:

@Test
public void testPutThrowsIllegalStateException() {
    assertThatIllegalArgumentException().isThrownBy(() -> llmm.put("A", null));
    assertThatIllegalArgumentException().isThrownBy(() -> llmm.put(null, 1));
    assertThatIllegalArgumentException().isThrownBy(() -> llmm.put(null, null));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145915&siteId=1