在 Java 单元测试中,如何断言数字在给定范围内?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9712648/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:33:11  来源:igfitidea点击:

In a Java unit test, how do I assert a number is within a given range?

javajunit

提问by klenwell

Coming to Java from Python. I recognize this is pretty basic, but it doesn't seem this has been asked here yet and Google is being coy with me.

从 Python 转为 Java。我承认这是非常基本的,但这里似乎还没有问过这个问题,谷歌对我很害羞。

In Python, I'd simply do something like this but Java objects:

在 Python 中,我只会做这样的事情,但 Java 对象:

assertTrue(min <= mynum and mynum <= max);

采纳答案by ruakh

I'd write:

我会写:

assertTrue("mynum is out of range: " + mynum, min <= mynum && mynum <= max);

but technically you just need:

但从技术上讲,您只需要:

assertTrue(min <= mynum && mynum <= max);

Either way, be sure to write &&and not and.

无论哪种方式,一定要写&&而不是and.

回答by hvgotcodes

assertTrue(min <= mynum && mynum <= max, "not in range");

assertTrue(min <= mynum && mynum <= max, "not in range");

the comment at the end is optional. Basically the same as the python version, except the &&.

最后的注释是可选的。基本上与 python 版本相同,除了&&.

回答by Wyzard

Use &&rather than and; other than that, what you wrote should work.

使用&&而不是and; 除此之外,你写的应该有效。

回答by Balaswamy Vaddeman

you can use Hamcrestlibrary too ,this is more readable.

您也可以使用Hamcrest库,这更具可读性。

assertThat(mynum,greaterThanOrEqualTo(min));

assertThat(mynum,lessThanOrEqualTo(max));

I dont know whether those two lines can be merged.

我不知道这两行是否可以合并。

回答by seeker

Extending on thisanswer: you can combine the two with allOf.

扩展答案:您可以将两者与allOf.

assertThat(mynum, allOf(greaterThanOrEqualTo(min),lessThanOrEqualTo(max)));

The OR equivalent in Hamcrest is anyOf.

Hamcrest 中的 OR 等价物是anyOf

回答by Jonathan

If you use AssertJit becomes evenmore readable:

如果你使用AssertJ它变得甚至更加易读:

assertThat(mynum).isGreaterThanOrEqualTo(min).isLessThanOrEqualTo(max);

Plus the AssertionErrorbeats the assertTrueversion as you don't need to supply a description, e.g.:

加上AssertionError击败assertTrue因为你并不需要提供一个描述,如版本:

java.lang.AssertionError: 
Expecting:
 <10>
to be less than or equal to:
 <42> 

If you're using Java 8 and AssertJ 3.0.0, you can use a lambda to specify it:

如果您使用的是 Java 8 和 AssertJ 3.0.0,则可以使用 lambda 来指定它:

assertThat(mynum).matches(actual -> actual >= min && actual <= max);

回答by MariuszS

I will use AssertJas Jonathan said, but with simpler assertions :)

我将像乔纳森所说的那样使用AssertJ,但使用更简单的断言:)

 assertThat(mynum).isBetween(min, max);

I think this is the coolest solution :)

我认为这是最酷的解决方案:)