[英]PowerMock, mock a static method, THEN call real methods on all other statics
I'm setting up mocking a class' static methods.我正在设置模拟类的静态方法。 I have to do this in a
@Before
-annotated JUnit setup method.我必须在
@Before
JUnit 设置方法中执行此操作。
My goal is to setup the class to call real methods, except for those methods I explicitly mock.我的目标是设置类来调用真正的方法,除了我明确模拟的那些方法。
Basically:基本上:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class);
// mock out certain methods...
when(StaticUtilClass.someStaticMethod(anyString())).thenReturn(5);
// Now have all OTHER methods call the real implementation??? How do I do this?
}
The problem I'm running into is that within StaticUtilClass
the method public static int someStaticMethod(String s)
unfortunately throws a RuntimeException
if supplied with a null
value.我
StaticUtilClass
的问题是,在StaticUtilClass
,如果提供null
值,方法public static int someStaticMethod(String s)
不幸地抛出RuntimeException
。
So I can't simply go the obvious route of calling real methods as the default answer as below:所以我不能简单地走调用真实方法作为默认答案的明显路线,如下所示:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class, CALLS_REAL_METHODS); // Default to calling real static methods
// The below call to someStaticMethod() will throw a RuntimeException, as the arg is null!
// Even though I don't actually want to call the method, I just want to setup a mock result
when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5);
}
I need to set the default Answer to call real methods on all other static methods after I mock the results from the method I'm interested in mocking.在我对我感兴趣的模拟方法的结果进行模拟后,我需要设置默认答案以在所有其他静态方法上调用真实方法。
Is this possible?这可能吗?
What are you looking for is called partial mocking .你在找什么叫做部分嘲笑。
In PowerMock you can use mockStaticPartial method.在 PowerMock 中,您可以使用mockStaticPartial方法。
In PowerMockito you can use stubbing, which will stub only the method defined and leave other unchanged:在 PowerMockito 中,您可以使用存根,它只会存根定义的方法而其他保持不变:
PowerMockito.stub(PowerMockito.method(StaticUtilClass.class, "someStaticMethod")).toReturn(5);
also don't forget about the也不要忘记
@PrepareForTest(StaticUtilClass.class)
Though I'm late to the party, but we can achieve partial mocking and override the default behavior of mocked object by explicitly specifying it.虽然我迟到了,但是我们可以通过显式指定来实现部分模拟并覆盖模拟对象的默认行为。
Below example show how we can make PowerMockito
to call real methods if behavior isn't defined explicitly:下面的例子展示了如果行为没有明确定义,我们如何让
PowerMockito
调用真正的方法:
eg PowerMockito.mockStatic(MyClass.class, new CallsRealMethods());
例如
PowerMockito.mockStatic(MyClass.class, new CallsRealMethods());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.