我正在设置一个类的静态方法。我必须在@Before
注释的JUnit设置方法中执行此操作。
我的目标是设置类来调用实际方法,除了我明确模拟的那些方法。
基本上:
@Before
public void setupStaticUtil() {
PowerMockito.mockStatic(StaticUtilClass.class);
when(StaticUtilClass.someStaticMethod(anyS
特林()))thenReturn(5)。 //嘲笑某些方法......
// Now have all OTHER methods call the real implmentation??? How do I do this?
}
我遇到的问题是,在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)