首页 文章

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

提问于
浏览
2

我正在编写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);
}

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

无论如何都要在 JUnit4 way 中使用 null 消息测试异常 . (我知道我可以 grab 异常并亲自检查条件) .

1 回答

  • 2

    使用 org.hamcrest.Matcherorg.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);
    }
    

相关问题