JUnit:使用Java 8和AssertJ 3.0.0测试异常
生活随笔
收集整理的這篇文章主要介紹了
JUnit:使用Java 8和AssertJ 3.0.0测试异常
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java 8的AssertJ 3.0.0發行版比以前更容易測試異常。 在我以前的一篇博客文章中,我描述了如何利用純 Java 8實現此目的,但是使用AssertJ 3.0.0可能會刪除我創建的許多代碼。
警告:此博客文章主要包含代碼示例。
SUT –被測系統
我們將測試以下2類拋出的異常。
第一個:
class DummyService {public void someMethod() {throw new RuntimeException("Runtime exception occurred");}public void someOtherMethod(boolean b) {throw new RuntimeException("Runtime exception occurred",new IllegalStateException("Illegal state"));} }第二個:
class DummyService2 {public DummyService2() throws Exception {throw new Exception("Constructor exception occurred");}public DummyService2(boolean dummyParam) throws Exception {throw new Exception("Constructor exception occurred");} }assertThatThrownBy()示例
注意:為了使以下代碼正常工作,需要靜態導入org.assertj.core.api.Assertions.assertThatThrownBy 。
@Test public void verifiesTypeAndMessage() {assertThatThrownBy(new DummyService()::someMethod) .isInstanceOf(RuntimeException.class).hasMessage("Runtime exception occurred").hasNoCause(); }@Test public void verifiesCauseType() {assertThatThrownBy(() -> new DummyService().someOtherMethod(true)).isInstanceOf(RuntimeException.class).hasMessage("Runtime exception occurred").hasCauseInstanceOf(IllegalStateException.class); }@Test public void verifiesCheckedExceptionThrownByDefaultConstructor() {assertThatThrownBy(DummyService2::new).isInstanceOf(Exception.class).hasMessage("Constructor exception occurred"); }@Test public void verifiesCheckedExceptionThrownConstructor() {assertThatThrownBy(() -> new DummyService2(true)).isInstanceOf(Exception.class).hasMessage("Constructor exception occurred"); }所提供的斷言來自AbstractThrowableAssert ,您可以使用更多的斷言!
沒有異常拋出!
以下測試將失敗,因為不會引發異常:
@Test public void failsWhenNoExceptionIsThrown() { assertThatThrownBy(() -> System.out.println()); }消息是:
java.lang.AssertionError: Expecting code to raise a throwable.AAA風格
如果您希望區分測試的行動階段和斷言階段以提高可讀性,則還可以:
@Test public void aaaStyle() {// arrangeDummyService dummyService = new DummyService();// actThrowable throwable = catchThrowable(dummyService::someMethod);// assertassertThat(throwable).isNotNull().hasMessage("Runtime exception occurred"); }參考文獻
- GitHub上提供了本文的源代碼 (請查看com.github.kolorobot.assertj.exceptions包)
- AssertJ 3.0.0 for Java 8版本
翻譯自: https://www.javacodegeeks.com/2015/04/junit-testing-exceptions-with-java-8-and-assertj-3-0-0.html
總結
以上是生活随笔為你收集整理的JUnit:使用Java 8和AssertJ 3.0.0测试异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jsf 传参数_在JSF 2中对定制验证
- 下一篇: 运气爆棚啥意思 怎么理解运气爆棚的意思