How can I test if a particular exception is not thrown?
我可以测试是否没有抛出特定的异常吗?
使用
但我怎么能否定这个呢?
如果要测试是否在可能抛出其他异常的情况下抛出特定异常,请尝试以下操作:
1 2 3 4 5 6 7 8 9 10 11 | try { myMethod(); } catch (ExceptionNotToThrow entt){ fail("WHOOPS! Threw ExceptionNotToThrow" + entt.toString); } catch (Throwable t){ //do nothing since other exceptions are OK } assertTrue(somethingElse); //done! |
catch-exception使Freiheit的例子更加简洁:
1 2 | catchException(a).myMethod(); assertFalse(caughtException() instanceof ExceptionNotToThrow); |
您可以使用assertj执行以下操作
如果你想检查是否没有抛出异常
1 2 3 | Throwable throwable = catchThrowable(() -> sut.method()); assertThat(throwable).isNull(); |
或者你期望扔掉
1 2 3 4 | Throwable throwable = catchThrowable(() -> sut.method()); assertThat(throwable).isInstanceOf(ClassOfExecption.class) .hasMessageContaining("expected message"); |