[英]In a Java unit test, how do I assert a number is within a given range?
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);
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
。
If you use AssertJ it becomes even more readable:如果你使用AssertJ它变得更加可读:
assertThat(mynum).isGreaterThanOrEqualTo(min).isLessThanOrEqualTo(max);
Plus the AssertionError
beats the assertTrue
version as you don't need to supply a description, eg:加上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);
Using AssertJ with isCloseTo(expected, offset)
:将AssertJ与isCloseTo(expected, offset)
:
BigDecimal maxNegativeOffset = new BigDecimal("0.0004");
BigDecimal actual = new BigDecimal("0.0005");
BigDecimal maxPositiveOffset = new BigDecimal("0.0006");
Offset<BigDecimal> offset = Offset.offset(new BigDecimal("0.0001"));
Assertions.assertThat(actual)
.isCloseTo(maxNegativeOffset, offset)
.isCloseTo(maxPositiveOffset, offset);
Maven dependency: https://mvnrepository.com/artifact/org.assertj/assertj-core Maven 依赖: https : //mvnrepository.com/artifact/org.assertj/assertj-core
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 版本相同。
Use &&
rather than and
;使用&&
而不是and
; other than that, what you wrote should work.除此之外,你写的应该有效。
import static com.google.common.truth.Truth.assertThat;
assertThat(actualDouble).isWithin(tolerance).of(expectedDouble);
assertThat(0.0999999).isWithin(1E-6).of(0.1d);
assertThat(90d).isWithin(10d).of(100d); // success
assertThat(105d).isWithin(10d).of(100d); // success
assertThat(110d).isWithin(10d).of(100d); // success
assertThat(89d).isWithin(10d).of(100d); // fails
assertThat(111d).isWithin(10d).of(100d); // fails
java.lang.AssertionError: <111.0> and <100.0> should have been finite values within <10.0> of each other
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.