PowerMock,模拟静态方法,然后在所有其他静态上调用真实方法
我正在设置一个类的静态方法。 我必须在@Before
-annotated JUnit设置方法中执行此操作。
我的目标是设置类来调用实际方法, 除了我明确模拟的那些方法。
基本上:
@Before public void setupStaticUtil() { PowerMockito.mockStatic(StaticUtilClass.class); when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5); // mock out certain methods... // Now have all OTHER methods call the real implmentation??? How do I do this? }
我StaticUtilClass
的问题是,在StaticUtilClass
,方法public static int someStaticMethod(String s)
不幸地抛出RuntimeException
如果提供了null
值)。
因此,我不能简单地将调用实际方法的明显路线作为默认答案,如下所示:
@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); }
我需要设置默认的Answer来调用所有其他静态方法的真实方法,我模拟了我对模拟感兴趣的方法的结果。
这可能吗?
你在寻找什么被称为部分嘲笑 。
在PowerMock中,您可以使用mockStaticPartial方法。
在PowerMockito中,您可以使用stubbing,它将仅存根定义的方法并保留其他不变的:
PowerMockito.stub(PowerMockito.method(StaticUtilClass.class, "someStaticMethod")).toReturn(5);
也别忘了
@PrepareForTest(StaticUtilClass.class)