从Python转到Java。我知道这很基础,但似乎还没有人在这里问过这个问题,而且Google对我也不友好。
在Python中,我会像这样处理Java对象:
assertTrue(min <= mynum and mynum <= max);
我会写:
assertTrue("mynum is out of range: " + mynum, min <= mynum && mynum <= max);
但从技术上讲,您只需要:
assertTrue(min <= mynum && mynum <= max);
无论哪种方式,一定要写成&&
而不是and
。
assertThat(mynum,greaterThanOrEqualTo(min));
assertThat(mynum,lessThanOrEqualTo(max));
这些行可以通过 allOf
合并,方法如下:
assertThat(mynum, allOf(greaterThanOrEqualTo(min),lessThanOrEqualTo(max)));
扩展这个答案:你可以通过allOf
结合两者。
assertThat(mynum, allOf(greaterThanOrEqualTo(min),lessThanOrEqualTo(max)));
anyOf
。assertThat(mynum).isGreaterThanOrEqualTo(min).isLessThanOrEqualTo(max);
此外,AssertionError
版本比 assertTrue
更好,因为您不需要提供描述,例如:
java.lang.AssertionError:
Expecting:
<10>
to be less than or equal to:
<42>
assertThat(mynum).matches(actual -> actual >= min && actual <= max);
assertTrue
和Hamcrest版本相比,这个断言读起来更自然。 - Jonathan使用 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 依赖:https://mvnrepository.com/artifact/org.assertj/assertj-core
assertTrue(min <= mynum && mynum <= max, "not in range");
末尾的注释是可选的。基本上与Python版本相同,只是使用了&&
。
使用 &&
而不是 and
;除此之外,你所写的应该可以工作。
我也在寻找解决方案,但对现有的解决方案不满意。在JUnit5中,可以使用assertEquals
来实现所需的功能。
// Asserts that expected and actual are equal within the given delta.
assertEquals(expected, actual, delta);
您可以在JUnit5文档中找到更多信息。
assertEquals(expected, actual, delta)
和“delta”值的文章。似乎delta/epsilon表示实际输出的可接受精度或接受的误差范围。您能否解释一下如何在以下场景中使用此函数。例如:变量“position”的值必须介于MIN_POSITION = 1和MAX_POSITION = 4之间。 - undefinedassertEquals(2.5, actual, 1.5)
。起初可能不太清楚它的意思是actual在1到4之间。但至少你不需要任何其他库或复杂的语法。 - undefined来自真相。
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
and
不是 Java 关键字,你需要使用&&
。 - Oliver Charlesworthimport static org.junit.Assert.assertTrue
也有帮助。谢谢大家! - klenwell