首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用Junit 4框架的selenium中,即使assert语句失败,也可以继续执行

在使用Junit 4框架的selenium中,即使assert语句失败,也可以继续执行
EN

Stack Overflow用户
提问于 2016-07-23 19:11:56
回答 3查看 5.5K关注 0票数 0

在我的测试用例中,必须使用多个断言。问题是,如果一个断言失败,那么执行就会停止。我希望该测试用例即使在遇到断言失败后也能继续执行,并且在执行后显示所有断言失败。

例如:

代码语言:javascript
复制
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失败,那么它应该继续执行,并在完成执行后显示所有失败。

EN

回答 3

Stack Overflow用户

发布于 2016-07-23 20:00:20

对于纯粹的JUnit解决方案,可以使用ErrorCollector TestRule来处理断言。

在测试执行完成之前,ErrorCollector规则不会报告。

代码语言:javascript
复制
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);
        }
    }
}

在您的特定示例中:

代码语言:javascript
复制
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);

会变成

代码语言:javascript
复制
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);
票数 4
EN

Stack Overflow用户

发布于 2016-07-23 19:49:57

您正在寻找的功能称为软断言,请尝试assertj

代码语言:javascript
复制
    SoftAssertions soft = new SoftAssertions();
    soft.assertThat(<things>).isEqualTo(<other_thing>);
    soft.assertAll();

软断言将允许执行下一步,而不会在失败时抛出异常。在assertAll()方法的最后,一次性抛出所有收集到的错误。

票数 1
EN

Stack Overflow用户

发布于 2016-07-23 21:00:24

这里的另一种选择是一个最佳实践,许多人认为您无论如何都应该这样做:在每个测试用例中只放置一个 assert。

通过这样做,每个潜在的失败都以某种方式相互隔离;您可以直接获得您正在寻找的东西-正如JUnit将确切地告诉您,哪些测试失败了,哪些通过了。而不需要引入其他概念。

(您知道,即使像ErrorCollector或SoftAssertions这样的其他概念非常容易使用-它们也会给您的代码增加一点复杂性;使其更难阅读和理解)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38541105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档