ExpectedException.expectMessage((String) null) 不起作用

Cod*_*der 4 java junit junit4

我正在编写 JUnit4 单元测试,并且有一个条件,我需要断言null消息引发了异常。

@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);
}
Run Code Online (Sandbox Code Playgroud)

该行正确mPackage.getInfo(null)抛出带有null消息的异常,但 JUnit 测试失败并显示消息:

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
Run Code Online (Sandbox Code Playgroud)

无论如何,是否可以通过JUnit4 方式使用null消息来测试异常。(我知道我可以捕获异常并自己检查条件)。

Cod*_*der 6

使用org.hamcrest.Matcherwithorg.hamcrest.core.IsNull对我有用。

语法是,

@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);
}
Run Code Online (Sandbox Code Playgroud)