java - Powermockito 模拟静态方法匹配器不起作用
问题描述
当我尝试使用字符串输入模拟静态方法时,当我给出特定字符串时,模拟的存根会被执行,但是当我使用 anyString() 时,它不会按预期工作。
public class Foo {
public static String staticInput(String s) {
System.out.println("staticInput called");
return "static " + s;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class})
public class TestMockito {
@Test
public void test1() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.doReturn("dummyStaticStub").when(Foo.class, "staticInput", "1");
System.out.println(Foo.staticInput("1"));
}
@Test
public void test2() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.doReturn("dummyStaticIn").when(Foo.class, "staticInput", anyString());
System.out.println(Foo.staticInput("1"));
}
}
test1 打印:
dummyStaticStub
test2 打印:
staticInput 称为
静态 1
解决方案
您可以稍微改变方法并PowerMockito.mockStatic
改用
@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class})
public class TestMockito {
@Test
public void test1() throws Exception {
PowerMockito.mockStatic(Foo.class);
Mockito.when(Foo.staticInput("1")).thenReturn("dummyStaticStub");
System.out.println(Foo.staticInput("1"));
}
@Test
public void test2() throws Exception {
PowerMockito.mockStatic(Foo.class);
PowerMockito.when(Foo.staticInput(anyString())).thenReturn("dummyStaticIn");
System.out.println(Foo.staticInput("1"));
}
}
推荐阅读
- xcode10 - Xcode10.0 (10A255) import intent xx.h 出现错误
- java - 在将一个文件的内容复制到另一个文件时,“'”正在转换为“’”
- vhdl - 为什么我会得到这个“4 个可能的定义”VHDL 连接错误
- angular - 在订阅方法中成功添加到数据库后,Angular 6 和 Angular 材质对话框未打开
- python - SQLAlchemy 查询数据库并显示为 html 表单
- android - Android Room - 关系和 LiveData
- php - 允许从 Woocommerce 的购物车中删除自动添加的产品
- node.js - 获取从 azure 主题获取消息的订阅客户端中的总消息计数
- python-3.x - Python对具有不同属性的标签进行排序
- c# - 如何检查外部进程打开的excel文件