如何根据 2 个或更多期望值断言实际值?

发布于 2024-11-08 02:03:23 字数 216 浏览 14 评论 0原文

我正在测试一种方法,看看它是否返回正确的字符串。该字符串由许多行组成,这些行的顺序可能会发生变化,因此通常会给出 2 种可能的组合。该顺序对我的申请并不重要。

但是,由于行的顺序可能会发生变化,因此仅编写 Assert 语句是行不通的,因为有时它会通过测试,有时会无法通过测试。

那么,是否可以编写一个测试,根据 2 个或更多预期字符串值断言实际字符串值,并查看它是否等于其中任何一个?

I'm testing a method to see if it returns the correct string. This string is made up of a lot of lines whose order might change, thus usually giving 2 possible combinations. That order is not important for my application.

However, because the order of the lines might change, writing just an Assert statement will not work, since sometimes it will pass the test, and sometimes it will fail the test.

So, is it possible to write a test that will assert an actual string value against 2 or more expected string values and see if it is equal to any of them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

寂寞笑我太脆弱 2024-11-15 02:03:24

考虑编写一个方法返回的自定义 hamcrest 匹配器,在本例中 containsOneOf,即:

assertThat(myString, containsOneOf("value1", "value2"));

为了与“xUnit 模式”保持一致,您应该避免匹配器中的条件逻辑,带有break语句的循环就足够了。

查看 HamcrestxUnit 模式 了解更多信息。

Consider writing a custom hamcrest matcher returned by a method, in this case containsOneOf, i.e.:

assertThat(myString, containsOneOf("value1", "value2"));

In keeping with the "xUnit patterns" you should avoid conditional logic in your matcher, a loop with a break statement should suffice.

Have a look at Hamcrest and xUnit Patterns for more information.

尸血腥色 2024-11-15 02:03:24

使用 AssertTrue 的简单解决方案。
只需创建一个 List.of() 预期值并检查它是否包含预期值。

assertTrue(List.of("expected_1", "expected_2").contains("actual))

Simple solution using AssertTrue.
Just create a List.of() the expected values and check is it contains the expected value.

assertTrue(List.of("expected_1", "expected_2").contains("actual))
笔芯 2024-11-15 02:03:24

如果一行的内容是固定的,您可以在比较之前在行结尾处将其拆分。然后简单地将每一行与一组预期值进行比较。
像这样的事情:

   Set<String> expectedValues = ...
   String[] split = text.split("\n");
   for(String str : split) {
      assert(expectedValues.contains(str));
   }

如果您想检查是否存在所有预期值,您可以断言 expectedValue.remove(str) == true 并在循环后断言 Set 为空。如果某些行可能会出现多次,则必须使用 Bag 而不是 Set。

If the content for a line is fixed you can split it at line endings before comparing. Then simply compare each line to a set of expected values.
Something like this:

   Set<String> expectedValues = ...
   String[] split = text.split("\n");
   for(String str : split) {
      assert(expectedValues.contains(str));
   }

If you want to check that all expected values are present you can assert that expectedValue.remove(str) == true and assert after the loop that the Set is empty. If some lines may occur multiple times you have to use a Bag instead of a Set.

分開簡單 2024-11-15 02:03:24

最简单/最有效的可能是

assert str.equals(result1) || str.equals(result2);

当您没有打开断言时,这实际上不会产生任何开销。

The simplest/most efficient might be

assert str.equals(result1) || str.equals(result2);

This will effectively have no overhead when you don't have assertions turned on.

段念尘 2024-11-15 02:03:24

我认为你可以只使用assertTrue:

assertTrue(testString.matches("string1|string2"));

I think you can just use assertTrue:

assertTrue(testString.matches("string1|string2"));

不羁少年 2024-11-15 02:03:24

假设被测试的方法返回一个数组,您可以使用 Hamcrest 的 arrayContainingInAnyOrder

assertThat(result, is(arrayContainingInAnyOrder("value1", "value2", "value")))

注意:使用 is 包装器完全是可选的,仅用作可读性糖。

Assuming the method under test returns an array, you could test using Hamcrest's arrayContainingInAnyOrder.

assertThat(result, is(arrayContainingInAnyOrder("value1", "value2", "value")))

Note: use of is wrapper is purely optional, used only as readability sugar.

转角预定愛 2024-11-15 02:03:24

如果您没有或无法使用除 junit core 之外的第三方库,您可以使用这个小帮助器方法:

public static void assertListContains(List<Object> expected, Object actual) {
    if (!expected.contains(actual)) {
        fail("Expected: " + expected + " Actual: " + actual);
    }
}

与其他解决方法答案相比,优点是您可以看到预期的内容和实际的内容:

org.opentest4j.AssertionFailedError: Expected: [1, 2] Actual: 3

If you do not have or can't use third-party libraries except junit core, you can use this small helper method:

public static void assertListContains(List<Object> expected, Object actual) {
    if (!expected.contains(actual)) {
        fail("Expected: " + expected + " Actual: " + actual);
    }
}

Advantage, in contrast to other workaround answers, is that you can see what was expected and what was actual:

org.opentest4j.AssertionFailedError: Expected: [1, 2] Actual: 3
霊感 2024-11-15 02:03:24

这是一篇旧文章,但我想要一个简单的本地答案,而不需要添加额外的库。 :)

所以我这么做了:

String e
e = "ear"
j = "jars"

assert (j == "jar" || e == "ear")

或者如果你希望它们都是真的

assert (j == "jar" && e == "ear")

It's an old post, but I wanted to have an native easy answer, without having extra libraries to add. :)

So I did :

String e
e = "ear"
j = "jars"

assert (j == "jar" || e == "ear")

or if you want them to be both true

assert (j == "jar" && e == "ear")
稚气少女 2024-11-15 02:03:24

在我看来,这是最简单的解决方案......

assert obtainedValue in [acceptedValue1, acceptedValue2]

This seems to me like the simplest solution ...

assert obtainedValue in [acceptedValue1, acceptedValue2]
浅黛梨妆こ 2024-11-15 02:03:23

使用 Hamcrest CoreMatcher(包含在 JUnit 4.4 和稍后)和assertThat():

assertThat(myString, anyOf(is("value1"), is("value2")));

Using the Hamcrest CoreMatcher (included in JUnit 4.4 and later) and assertThat():

assertThat(myString, anyOf(is("value1"), is("value2")));
素罗衫 2024-11-15 02:03:23

我会使用 AssertJ

import static org.assertj.core.api.Assertions.*;

assertThat("hello").isIn("hello", "world");

它更简洁,而且当断言失败时会给你一条描述性消息。

I would use AssertJ for this:

import static org.assertj.core.api.Assertions.*;

assertThat("hello").isIn("hello", "world");

It's more concise and it will give you a descriptive message when the assertion fails.

尤怨 2024-11-15 02:03:23

我正在使用以下内容,希望这会有所帮助:

String expectedTitles[] = {"Expected1","Expected2"};
List<String> expectedTitlesList = Arrays.asList(expectedTitles);

assertTrue(expectedTitlesList.contains((actualTitle)));

I am using the following, I hope this would help:

String expectedTitles[] = {"Expected1","Expected2"};
List<String> expectedTitlesList = Arrays.asList(expectedTitles);

assertTrue(expectedTitlesList.contains((actualTitle)));
摘星┃星的人 2024-11-15 02:03:23

您可以使用 Hamcrest 来实现此目的:(

assertThat(testString, anyOf(
    containsString("My first string"), 
    containsString("My other string")));

我看到 Joachim 的回答非常相似 (+1)。 ..我将添加这个作为另一个例子。)

You can use Hamcrest for this:

assertThat(testString, anyOf(
    containsString("My first string"), 
    containsString("My other string")));

(I see Joachim just answered very similarly (+1)... i'll add this as another example.)

只为守护你 2024-11-15 02:03:23

我阅读了所有答案,但对我来说最紧凑和最具表现力的一个是使用 Hamcrest 的 isOneOf ,它已经包含在 JUnit 中,

assertThat(result, isOneOf("value1", "value2"));

它在失败时给你一个很好的错误消息。

java.lang.AssertionError: 
Expected: one of {"value1", "value2"}
     but: was "value"
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
[...]

I read all answers, but the one that seems most compact and expressive to me is using Hamcrest's isOneOf which is already included in JUnit

assertThat(result, isOneOf("value1", "value2"));

which gives you a nice error message when failing.

java.lang.AssertionError: 
Expected: one of {"value1", "value2"}
     but: was "value"
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
[...]
风追烟花雨 2024-11-15 02:03:23

如果您使用 junit,我只需执行以下操作:

assertTrue(myString.equals("Value1") || myString.equals("Value"));

If your using junit I'd just do something like the following:

assertTrue(myString.equals("Value1") || myString.equals("Value"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文