【发布时间】:2016-04-23 12:22:52
【问题描述】:
Powermock 有什么理由不模拟静态方法调用,而是在 then() 语句中调用初始方法?
这是我有一系列方法调用的情况:
TestClass 方法 -call-> Class1 方法 -call-> Class2 静态方法 -call-> Class3 静态方法 -call-> Class4 方法。
Class4 方法尝试查找上下文中不存在的对象并挂起,因此我尝试使用 Powermock 模拟公共静态 Class3 方法。
所有类和方法都是非最终的。 我使用TestNg。我的 testMethod 有一个 @PrepareForTest 我尝试了以下方法来模拟方法调用:
PowerMockito.mockStatic(Class3.class);
when(Class3.callEvilMethod()).thenReturn("test");
OR 代替 when-thenReturn:
doReturn("test").when(Class3.callEvilMethod());
或
doAnswer(new Answer() {methos that returns test"}).when(Class3.callEvilMethod());
或
PowerMockito.stub(PowerMockito.method(Class3.class, "callEvilMethod")).toReturn("test");
但是当我运行测试时,初始 Class3.callEvilMethod() 在 when 语句中被调用。我不知道为什么。不应该嘲讽吗?
编辑:我调整了我的测试以向您展示它的样子:
@PrepareForTest( { Class1.class, Class2.class, Class3.class})
public class TestClass extends AbstractTest {
private Class1 class1;
@BeforeMethod
public void setUp() throws Exception {
class1 = new Class1() {
}
@Test
public void testMethod() throws Exception {
// Create various objects in Db, do other method calls, then:
PowerMockito.mockStatic(Class3.class);
// PowerMockito.suppress(PowerMockito.method(Class3.class, "evilMethod"));
// PowerMockito.when(Class3.EvilMethod()).thenReturn("test");
// doReturn("test").when(Class3.evilMethod());
// PowerMockito.stub(PowerMockito.method(Class3.class, "evilMethod")).toReturn("test");
class1.callMethod();
}
}
【问题讨论】:
-
我们能看到整个测试吗? (特别是你使用的
@PrepareForTest) -
@RC。在最初的问题中添加了我的测试示例。
-
好的,你是在
setup中继承Class1吗?如果是这样,那可能就是问题所在。我也会尝试在setup的开头移动PowerMockito.mockStatic(Class3.class); -
@RC。不,我只是在创建 Class1 的一个实例。并且将 PowerMockito.mockStatic(Class3.class) 移动到 setUp 的开头不会改变任何东西:(
标签: java unit-testing mocking static-methods powermock