gpt4 book ai didi

java - PowerMock 和 Mockito 的静态模拟不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 19:39:41 25 4
gpt4 key购买 nike

我正在尝试验证 Collections.shuffle() 方法是否在我的一个类中被调用。我通读了有关 PowerMock 和 Mockito 的(小)文档,并通读了处理此问题但未得到解决的其他 SO 问题。

@RunWith(PowerMockRunner.class)
@PrepareForTest(Collections.class)
public class MyTest {

@Test
public void testShuffle() {
PowerMockito.mockStatic(Collections.class);
PowerMockito.doCallRealMethod().when(Collections.class);
Collections.shuffle(Mockito.anyListOf(Something.class));

ClassToTest test = new ClassToTest();
test.doSomething();

PowerMockito.verifyStatic(); // Verify shuffle was called exactly once
Collections.shuffle(Mockito.anyListOf(Something.class));
}
}

public class ClassToTest {
private final List<Something> list;
// ...
public void doSomething() {
Collections.shuffle(list);
// do more stuff
}
}

鉴于上面的代码,我希望单元测试通过。但是,单元测试失败如下:

Wanted but not invoked java.util.Collections.shuffle([]);
Actually, there were zero interactions with this mock.

我做错了什么?

谢谢

编辑:根据下面的建议,我尝试了以下操作,但我得到了同样的错误。

@RunWith(PowerMockRunner.class)
@PrepareForTest(Collections.class)
public class MyTest {

@Test
public void testShuffle() {
PowerMockito.mockStatic(Collections.class);

ClassToTest test = new ClassToTest();
test.doSomething();

PowerMockito.verifyStatic(); // Verify shuffle was called exactly once
Collections.shuffle(Mockito.anyListOf(Something.class));
}
}

最佳答案

这是一个相当古老的问题,但我仍然想澄清一下,接受的答案实际上是不正确的。通过执行以下代码,

PowerMockito.mockStatic(Collections.class);
Collections.shuffle(Mockito.anyListOf(Something.class));

之后所有的验证都会通过:

PowerMockito.verifyStatic(); // Verify shuffle was called exactly once
Collections.shuffle(Mockito.anyListOf(Something.class));

即使您不调用 test.doSomething();,答案中提供的测试仍然会通过。正确的测试方法是实际检查列表中的项目是否已正确排序。

关于java - PowerMock 和 Mockito 的静态模拟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17938997/

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