我要在 Util 类中模拟一个名为 toBeMockedFunction 的静态函数。该方法是从 toBeUnitTested 调用的,它是一个公共(public)静态 void 方法。我想要BeMocked函数什么都不做。我尝试了许多部分模拟和 stub 的方法(发布了此类 2 的片段),但无法成功。
请指出我做错了什么。
public class Util {
// Some code
public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) {
// some code
toBeMockedFunction(cb, "test", "test");
}
public static CustomObject toBeMockedFunction(CustomObject cb, String str1) {
// some code
}
}
下面是我的 junit 类
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Util.class})
public class UtilTest {
@Test
public void Test1() {
PowerMockito.spy(Util.class);
//mock toBeMocked function and make it do nothing
PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null);
Util.toBeUnitTested(cb, "test", "test");
}
}
方法2
PowerMockito.mockStatic(Util.class); PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod(); Util.toBeUnitTested(cb, "test", "test");
最佳答案
这是如何做到这一点的示例:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Util.class})
public class UtilTest {
@Test
public void Test1() {
PowerMockito.spy(Util.class);
PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString());
List<CustomObject2> customObject2List = new ArrayList<>();
customObject2List.add(new CustomObject2());
Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true);
}
}
请注意,您的 OP 代码无法编译。方法 toBeMockedFunction(CustomObject cb, String str1)
仅接收 2 个参数,而您使用 3 个参数进行调用:toBeMockedFunction(cb, "test", "test");
。正如您所看到的,我已将最后一个添加到方法签名中。
希望对你有帮助
关于junit - 无法使用 PowerMockito 部分模拟静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30233112/