在我的测试用例中,必须使用多个断言。问题是,如果一个断言失败,那么执行就会停止。我希望该测试用例即使在遇到断言失败后也能继续执行,并且在执行后显示所有断言失败。
例如:
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);在本例中,我希望如果assert对于condition2失败,那么它应该继续执行,并在完成执行后显示所有失败。
发布于 2016-07-23 20:00:20
对于纯粹的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);发布于 2016-07-23 19:49:57
您正在寻找的功能称为软断言,请尝试assertj
SoftAssertions soft = new SoftAssertions();
soft.assertThat(<things>).isEqualTo(<other_thing>);
soft.assertAll();软断言将允许执行下一步,而不会在失败时抛出异常。在assertAll()方法的最后,一次性抛出所有收集到的错误。
发布于 2016-07-23 21:00:24
这里的另一种选择是一个最佳实践,许多人认为您无论如何都应该这样做:在每个测试用例中只放置一个 assert。
通过这样做,每个潜在的失败都以某种方式相互隔离;您可以直接获得您正在寻找的东西-正如JUnit将确切地告诉您,哪些测试失败了,哪些通过了。而不需要引入其他概念。
(您知道,即使像ErrorCollector或SoftAssertions这样的其他概念非常容易使用-它们也会给您的代码增加一点复杂性;使其更难阅读和理解)
https://stackoverflow.com/questions/38541105
复制相似问题