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