2016-07-23 119 views
0

在我的測試案例中,它強制使用多個斷言。問題是,如果一個斷言失敗,那麼執行就會停止。我希望測試用例在遇到斷言失敗後繼續執行,並在執行後顯示所有斷言失敗。即使在使用Junit 4框架的selenium中斷言語句失敗時仍繼續執行

例如:

assertTrue("string on failure",condition1); 
assertTrue("string on failure",condition2); 
assertTrue("string on failure",condition3); 
assertTrue("string on failure",condition4); 
assertTrue("string on failure",condition5); 

在這裏,在這個例子中,我想,如果斷言爲條件2失敗,那麼就應該繼續執行並顯示完整的執行畢竟失敗。

回答

1

你正在尋找被稱爲軟斷言功能,嘗試assertj

SoftAssertions soft = new SoftAssertions(); 
    soft.assertThat(<things>).isEqualTo(<other_thing>); 
    soft.assertAll(); 

軟斷言將允許執行下一步而不進行破壞時拋出異常。在末尾assertAll()方法拋出所有收集錯誤在onece。

+0

但這是適用於Junit ....我認爲這是testng的東西 –

+0

AssertJ有作爲依賴的JUnit(https://mvnrepository.com/artifact/org.assertj/assertj-core/3.5.1)所以它應該工作它只是收集異常,並且一旦只有一個就會一下子全部嘔吐。所以這個概念絕對沒有與任何單元測試框架或語言綁定。實際上,這裏是在python中執行軟斷言(http://pythontesting.net/strategy/delayed-assert),它與@jeremiah提出的完全相似。 – pr4bh4sh

4

對於純粹的JUnit解決方案,請使用ErrorCollector TestRule來處理您的斷言。

ErrorCollector在測試執行完成之前,規則不會回報。

import org.hamcrest.core.IsEqual; 
import org.hamcrest.core.IsNull; 
import org.hamcrest.text.IsEmptyString; 
import org.junit.Rule; 
import org.junit.Test; 
import org.junit.rules.ErrorCollector; 

public class ErrorCollectorTest { 
    @Rule 
    public ErrorCollector collector = new ErrorCollector(); 

    @Test 
    public void testMultiAssertFailure() { 
     collector.checkThat(true, IsEqual.equalTo(false)); 
     collector.checkThat("notEmpty", IsEmptyString.isEmptyString()); 
     collector.checkThat(new Object(), IsNull.nullValue()); 
     collector.checkThat(null, IsNull.notNullValue()); 

     try { 
      throw new RuntimeException("Exception"); 
     } catch (Exception ex){ 
      collector.addError(ex); 
     } 
    } 
} 

在你的具體的例子:

assertTrue("string on failure",condition1); 
assertTrue("string on failure",condition2); 
assertTrue("string on failure",condition3); 
assertTrue("string on failure",condition4); 
assertTrue("string on failure",condition5); 

將成爲

Matcher<Boolean> matchesTrue = IsEqual.equalTo(true); 
collector.checkThat("String on Failure", condition1, matchesTrue); 
collector.checkThat("String on Failure", condition2, matchesTrue); 
collector.checkThat("String on Failure", condition3, matchesTrue); 
collector.checkThat("String on Failure", condition4, matchesTrue); 
collector.checkThat("String on Failure", condition5, matchesTrue); 
0

這裏的另一種選擇是最好的做法,很多人說你應該總是反正做:在每個測試用例中只有一個斷言。

通過這樣做,每一個潛在的失敗都會以某種方式彼此隔離;你直接得到你正在尋找的東西 - 正如JUnit會準確地告訴你,哪些測試失敗了,哪些測試失敗了。不需要介紹其他概念。

(你看,即使像ErrorCollector或SoftAssertions那些其他概念是很容易和簡單的使用 - 他們增加複雜性的一點點你的代碼,使它有點難以閱讀和理解)

+1

在* unit *測試中,最好每個測試只做一個斷言。隨着像Selenium這樣的工具被引入混合,測試不再是「單元」級測試,因爲它必須針對實時系統運行。這是一個'整合'測試。在集成級別的測試中,隔離驗證的願望通常以價格(時間/性能/反饋)爲代價,使得多斷言設施更易於接受。這一切都與測試面向的環境有關。我並不不同意你關於單元測試的陳述,但是整合這個規則並不穩定(以我的經驗) – Jeremiah

+0

ya ..我也想過那個..但是在許多情況下,例如驗證小節的UI(for例如登錄頁面),多重斷言是有道理的。此外,以上建議的解決方案僅添加1或2行代碼,而不是太複雜 –

相關問題