Sydney
Sydney

Reputation: 11

Java unit test with common code

I am new to Java so apologies in advance if this is a silly question.

I noticed that I'm writing redundant code as my test cases are testing similar behavior with different attributes of same object.

@Test
public void testInvalidA() {
    obj.setA(null)
    //verify exception thrown if A is null
}

@Test
public void testInvalidB() {
    obj.setB(null)
    //verify exception thrown if B is null
}

Is there a way that I could simplify this?

Thanks!

Upvotes: 1

Views: 1197

Answers (2)

slash_rick_dot
slash_rick_dot

Reputation: 923

There's nothing wrong with the way you were doing it -- in fact its preferable most of the time. But if your example is a simplification of complexity that repeats with a similar testable signature, you could try a bit of functional programming:

private void nullNotAllowed( Consumer<Object> method ) {
    try {
        method.accept( null );
        fail( "Null Not Allowed");
    }
    catch ( Exception e ) { /*pass*/ }
}

@Test public void nonNullableSetters() {
    YourClass subject = new YourClass();
    nullNotAllowed( subject::setA );
    nullNotAllowed( subject::setB );
}

Upvotes: 1

techtabu
techtabu

Reputation: 26967

You can use assertj. Example code would be like this,

@Test
public  void testObjectsAreValid() {
    assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(obj.setA(null);
    assertThatExceptionOfType(ExpectedException.class)
        .isThrownBy(obj.setB(null);
}

assertj provides direct methods for some common exceptions.

assertThatIllegalArgumentException().isThrownBy(() -> obj.setB(null));

Check here for more documentation. I agree with Dawood though, keep each test separate and clear.

Upvotes: 2

Related Questions