在 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
In a Java unit test, how do I assert a number is within a given range?
提问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
回答by seeker
回答by Jonathan
If you use AssertJit becomes evenmore readable:
如果你使用AssertJ它变得甚至更加易读:
assertThat(mynum).isGreaterThanOrEqualTo(min).isLessThanOrEqualTo(max);
Plus the AssertionError
beats the assertTrue
version 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);