gpt4 book ai didi

java - 可选是否级联?

转载 作者:行者123 更新时间:2023-12-01 10:45:31 25 4
gpt4 key购买 nike

级联返回Optional的模拟时会有什么行为?我的期望是the returned Optional object is also a mock .

但是,下面的测试表明情况并非如此:

@RunWith(JMockit.class)
public class CascadingTest {
public static interface Foo {
Optional<Bar> getOptionalBar();
}

public static interface Bar {
}

@Test
public void cascadingOptional(@Mocked final Foo foo) {
final Optional<Bar> opt = foo.getOptionalBar();
assertThat(opt.get(), is(not(nullValue())));
}
}

由于opt.get()抛出异常而进行的cascadingOptional测试:

java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at jmockit.CascadingTest.cascadingOptional(CascadingTest.java:39)

这似乎表明 opt 不是一个模拟。顺便说一句,如何(直接)检查对象是否是 JMockit 模拟?

谢谢

JMockit v1.17

最佳答案

mocking API documentation根据模拟方法的返回类型指定默认返回的内容:

If no result is recorded for a given expectation, then all matching invocations will return the appropriate default value according to the method return type:

  • Most java.lang types (String, Object, etc.): returns null.
  • java.math types (BigDecimal, etc.): returns null.
  • Primitive/wrapper types: returns the standard default value (false for boolean/Boolean, 0 for int/Integer, and so on).
  • java.util.List, java.util.Collection, or java.lang.Iterable: returns Collections.EMPTY_LIST.
  • java.util.Iterator or java.util.ListIterator: returns an empty iterator.
  • java.util.Set: returns Collections.EMPTY_SET.
  • java.util.SortedSet: returns an unmodifiable empty sorted set.
  • java.util.Map: returns Collections.EMPTY_MAP.
  • java.util.SortedMap: returns an unmodifiable empty sorted map.
  • java.util.Optional: returns Optional.empty().
  • Other reference types: returns a mocked instance through cascading.
  • Array types: returns an array with zero elements (empty) in each dimension.

关于java - 可选是否级联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34205972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com