[英]How to mock nested static methods using PowerMockito?
How can I mock nested static methods using PowerMockito? 如何使用PowerMockito模拟嵌套的静态方法? The following is a very simple example on how I want to use it. 以下是有关如何使用它的非常简单的示例。
Class: 类:
public class SomeClass {
public static String someMethodA(){
//some very important codes here
return someMethodB();
}
private static String someMethodB(){
return someMethodC();
}
private static String someMethodC(){
return "Some Text";
}
}
Already tried the following but did not work: 已经尝试了以下操作,但没有成功:
PowerMockito.mockStatic(SomeClass.class);
PowerMockito.stub(PowerMockito.method(SomeClass.class, "someMethodB")).toReturn("Some Other Text");
I wanted to run someMethodA() as is, which is why I want to stub someMethodB() instead. 我想按原样运行someMethodA(),这就是为什么我想存根someMethodB()的原因。 Is there anyway I can do this? 反正我能做到这一点吗? Hoping that there is a way without having to modify the access modifiers because the codes I am working with are legacy codes. 希望有一种方法无需修改访问修饰符,因为我正在使用的代码是旧代码。
You can spy
the private static methods. 您可以spy
私有静态方法。
Tested in JUnit4
在JUnit4
测试
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeClass.class)
public class SomeClassTest {
@Test
public void test() throws Exception {
spy(SomeClass.class);
when(SomeClass.class, "someMethodB").thenReturn("Some Other Text");
assertEquals("Some Other Text", SomeClass.someMethodA());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.