gpt4 book ai didi

java - Mockito.any 返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:02:30 30 4
gpt4 key购买 nike

我正在尝试使用这样的参数模拟一个静态方法:

Mockito.when(StaticClass.staticMethod(Mockito.any(A.class), 
Mockito.any(B.class), SomeEnum.FOO))
.thenReturn(true);

我添加了以下注释:

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Parameterized.class)
@PrepareForTest({StaticClass.class, A.class, B.class})

但是 Mockito.any 总是返回 null。为什么?

最佳答案

简答:使用 doReturn().when() 而不是 when().then()

长答案可以在这里找到: How do Mockito matchers work?

Matchers return dummy values such as zero, empty collections, or null.Mockito tries to return a safe, appropriate dummy value, like 0 foranyInt() or any(Integer.class) or an empty List foranyListOf(String.class). Because of type erasure, though, Mockitolacks type information to return any value but null for any()

NullPointerException or other exceptions: Calls towhen(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null),which you might have stubbed to throw an exception when receiving anull argument. Switching to doReturn(baz).when(foo).bar(any()) skipsthe stubbed behavior.

旁注:这个问题也可以这样描述,如何在对空参数进行前提条件检查的方法上使用 Mockito 匹配器?

关于java - Mockito.any 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139340/

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