我有两个类:
class Outer {
Inner inner = new Inner("value");
}
class Inner {
private final String value;
Inner(String value) {
this.value = value;
}
}
public Optional<Outer> getOptionalValue() {
return Optional.of(new Outer());
}
我的测试:public void testCLass() {
Assertions.assertThat(getOptionalValue())
.isPresent()
.map(v -> v.inner.value)
.isEqualTo("value");
}
我希望它会通过,因为 isPresent
展开 optional ,map
转换 Outer
进入 value
在最后一种方法中,我只是比较字符串。但它在最后一行显示消息失败:
Expecting:
<Optional[value]>
to be equal to:
<"value">
but was not.
我不知道为什么没有打开 optional
最佳答案
OptionalAssert
的 javadoc的map方法状态
Call
map
on theOptional
under test, assertions chained afterwards are performed on theOptional
resulting from themap
call.
但是,
isEqualTo
实际上是比较 AbstractAssert
的值作为一个整体。它不会被 OptionalAssert
覆盖比较封闭的值。一个 OptionalAssert
的值,Optional
本身,不等于 String
.你会想要使用
hasValue
Verifies that the actual
Optional
contains the given value (alias ofcontains(Object)
).Assertion will pass :
assertThat(Optional.of("something")).hasValue("something"); assertThat(Optional.of(10)).contains(10);
所以
Assertions.assertThat(getOptionalValue())
.isPresent()
.map(v -> v.inner.value)
.hasValue("value");
或者,因为 hasValue
实际执行 isPresent
内部检查,你可以使用Assertions.assertThat(getOptionalValue())
.map(v -> v.inner.value)
.hasValue("value");
关于java - 在 Optional 中使用 assertJ 断言值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62563313/