如何在 TestNG 中针对 2 个或更多预期值断言实际值

How to assert an actual value against 2 or more expected values in TestNG

自动化保险申请。为 selenium web 驱动程序测试编写 TestNG 断言以验证策略的开始日期,默认情况下是今天的日期。

但在某些情况下,可能是明天的日期,具体取决于保险公司和计划。我想将其包含在断言中。但我想验证这两个中的任何一个,开始日期=今天或明天。想要结合以下 2 个断言。

我可以通过创建第三个布尔变量并检查日期以查看它是否与其中一个匹配并使布尔值为真并进行布尔断言来做到这一点,任何人都知道直接在 testNG 中执行此操作的任何其他方法.

1.    Assert.assertEquals(start_date, date_today, "Assertion failed-  Start Date");

2.    Assert.assertEquals(start_date, date_tomorrow, "Assertion failed-  Start Date");

在 junit 中我们有类似

的东西
assertThat(result, isOneOf("value1", "value2"));

可用于断言类似情况。

我们可以在testNG中做同样的操作吗?

就像 this similar question 一样,不是隐含的。顺便说一句,JUnit 中的 assertThat 可能依赖于 Hamcrest 匹配器,也许是旧版本。不管怎样,你至少有以下选择:

  • 使用 TestNG 的 assertTrue
  • 使用额外的库,例如 Hamcrest, AssertJ,等等

依赖关系:

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.9.0</version>
        <scope>test</scope>
    </dependency>

代码:

import org.testng.annotations.Test;

import java.time.LocalDate;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertTrue;

public class SomeTest {
    @Test // compare strings (usually that's what you get as values from a webpage)
    public void shouldCheckMultipleStringValues() {
        // simulate some data
        String myText = "my text";

        // TestNG
        assertTrue(myText.equals("my text") || myText.equals("your text") || myText.equals("his text"));

        //Hamcrest
        assertThat(myText, anyOf(equalTo("my text"), equalTo("your text"), equalTo("his text")));

        // AssertJ
        assertThat(myText).isIn("my text", "your text", "his text");
    }

    @Test // but you can even compare dates if you need to
    public void shouldCheckMultipleDateValues() {
        // simulate some date
        LocalDate myDate = LocalDate.now();

        // simulate a bunch of expected dates
        LocalDate yesterday = LocalDate.now().minusDays(1);
        LocalDate now = LocalDate.now();
        LocalDate tomorrow = LocalDate.now().plusDays(1);

        // TestNG
        assertTrue(myDate.equals(yesterday) || myDate.equals(now) || myDate.equals(tomorrow));

        //Hamcrest
        assertThat(myDate, anyOf(equalTo(yesterday), equalTo(now), equalTo(tomorrow)));

        // AssertJ
        assertThat(myDate).isIn(yesterday, now, tomorrow);
        assertThat(myDate).isBetween(yesterday, tomorrow);
    }
}

我会计算天数并对这个数字做一个断言:

long days = ChronoUnit.DAYS.between(start_date, date_today);
assertTrue((days >= 0) && (days <= 1));