Java 我的测试用例中的 Junit 断言 OR 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19004611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Junit assert OR condition in my test case
提问by Leem.fin
In my test case, I get an integer value:
在我的测试用例中,我得到一个整数值:
int val = getXXX();
Then, I would like to check if val
either equals to 3 or equals to 5 which is OK in either case. So, I did:
然后,我想检查是否val
等于 3 或等于 5,这在任何一种情况下都可以。所以我做了:
assertTrue(val == 3 || val==5);
I run my test, the log shows val
is 5, but my above assertion code failed with AssertionFailedError. Seems I can not use assertTrue(...)
in this way, then, how to check true for OR condition?
我运行我的测试,日志显示val
为 5,但我上面的断言代码因AssertionFailedError失败。好像我不能这样使用assertTrue(...)
,那么,如何检查 OR 条件是否为真?
采纳答案by smajlo
ive tried to write quick test:
我试图编写快速测试:
@Test
public void testName() {
int i = 5;
junit.framework.Assert.assertTrue(i == 3 || i == 5);
}
its passing always so i guess there is some inbetween code when your value is changed. You can use
它总是通过所以我猜当你的值改变时会有一些中间代码。您可以使用
org.junit.Assert.assertEquals(5, i);
to check value - this assertion will print out nice info whats wrong, for example:
检查值 - 这个断言将打印出很好的信息什么是错的,例如:
java.lang.AssertionError:
Expected :4
Actual :5
回答by Joe
You can use Hamcrest matchersto get a clearer error message here:
您可以使用Hamcrest 匹配器在此处获得更清晰的错误消息:
int i = 2;
assertThat(i, Matchers.either(Matchers.is(3)).or(Matchers.is(5))
or
int i = 2;
assertThat(i, Matchers.anyOf(Matchers.is(3),Matchers.is(5)));
This will more clearly explain:
这将更清楚地说明:
Expected: (is <3> or is <5>)
but: was <2>
showing exactly the expectation and the incorrect value that was provided.
准确显示所提供的期望值和错误值。
回答by A. Rodas
While Harmcrest matchers can do the job, these constants can be easily refactored to a more meaninful constant, like a list of valid values. Then you can use the contains
method to check that the value is present in the list - IMO is also easier to read:
虽然 Harmcrest 匹配器可以完成这项工作,但这些常量可以轻松重构为更有意义的常量,例如有效值列表。然后您可以使用该contains
方法检查列表中是否存在该值 - IMO 也更易于阅读:
public class Foo {
public static final List<Integer> VALID_VALUES = Arrays.asList(3, 5);
}
@Test
public void testName() {
int i = 5;
Assert.assertTrue(Foo.VALID_VALUES.contains(i));
}
回答by Mis94
In my case I wanted to do some complex assertion logic, so I simply implemented a method that returns a boolean and it did the job, the way it would be implemented in this example is as follows:
在我的例子中,我想做一些复杂的断言逻辑,所以我简单地实现了一个返回布尔值的方法,它完成了工作,在这个例子中它的实现方式如下:
private Boolean is3or5(Integer val) {
if(val == 3 || val == 5) {
return true;
}
return false;
}
Then do the assertion:
然后做断言:
assertTrue(is3or5(val));
Of course the method can contain more complex logic if needed
当然,如果需要,该方法可以包含更复杂的逻辑