ExpectedException.expectMessage((String) null) 不工作
ExpectedException.expectMessage((String) null) is not working
我正在编写 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 方式 中使用 null
消息测试异常。 (我知道我可以捕获异常并自己检查条件)。
使用 org.hamcrest.Matcher
和 org.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);
}
我正在编写 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 方式 中使用 null
消息测试异常。 (我知道我可以捕获异常并自己检查条件)。
使用 org.hamcrest.Matcher
和 org.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);
}