Java ApacheCommons验证器和JUnit
我使用ApacheCommonsValidator在构建器模式中验证输入 在生成器上调用build后,将使用以下方法检查变量:Java ApacheCommons验证器和JUnit,java,exception,junit,Java,Exception,Junit,我使用ApacheCommonsValidator在构建器模式中验证输入 在生成器上调用build后,将使用以下方法检查变量: Validate.notNull(oranges, "Oranges was not set."); 当测试我的代码时,我可以看到当我没有设置oranges时,我确实得到了oranges没有设置的消息。但是,引发的异常仍然是NullPointerException 在我的单元测试中,我想检查是否使用了验证器并输出了一条消息,但要清楚地使用: @Test(expecte
Validate.notNull(oranges, "Oranges was not set.");
当测试我的代码时,我可以看到当我没有设置oranges时,我确实得到了oranges没有设置的消息。但是,引发的异常仍然是NullPointerException
在我的单元测试中,我想检查是否使用了验证器并输出了一条消息,但要清楚地使用:
@Test(expected = NullPointerException.class)
无论是否使用验证程序或设置消息,都将通过
是否有一种方法可以检查是否使用了验证器以及是否在JUnit中设置了消息?如果没有,是否有允许我执行此操作的库?您应该只检查代码的外部行为。在您的例子中,这是:它抛出一个带有适当消息的NullPointerException 测试异常有不同的方法,请参见。你总是可以使用JUnit的 使用Java8,您可以使用库提供的方法。它允许您使用
使用NullPointerException是故意的还是仅仅是Commons验证程序代码的副作用?
public class YourTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void test() {
...
thrown.expect(NullPointerException.class);
thrown.expectMessage("Oranges was not set.");
builder.build();
}
}
public class YourTest {
@Test
public void test() {
...
Throwable exception = exceptionThrownBy(() -> builder.build());
assertEquals(NullPointerException.class, exception.getClass());
assertEquals("Oranges was not set.", exception.getMessage());
}
}