Codebender Codebender - 3 months ago 11
Java Question

ExpectedException.expectMessage((String) null) is not working

I am writing JUnit4 unit tests and have a condition where I need to assert that an exception was thrown with

null
message.

@Rule
public final ExpectedException exception = ExpectedException.none();

@Test
public final void testNullException() throws Exception {
exception.expect(Exception.class);
exception.expectMessage((String) null);
mPackage.getInfo(null);
}


The line
mPackage.getInfo(null)
is throwing an Exception with
null
message properly, but the JUnit test is failing with the message:

java.lang.AssertionError:
Expected: (an instance of java.lang.Exception and exception with message a string containing null)
but: exception with message a string containing null message was null


Is there anyway to test for an exception with a
null
message in JUnit4 way. (I know I can catch the exception and check for the conditions myself).

Answer

Using org.hamcrest.Matcher with org.hamcrest.core.IsNull worked for me.

The syntax is,

@Rule
public final ExpectedException exception = ExpectedException.none();

@Test
public final void testNullException() throws Exception {
    exception.expect(Exception.class);
    Matcher<String> nullMatcher = new IsNull<>();
    exception.expectMessage(nullMatcher);
    mPackage.getInfo(null);
}