时间:2021-08-25 08:02:41 | 栏目:JAVA代码 | 点击:次
假如有下面一个类DemoStatic,它里面定义了各种静态方法,这些静态方法可能是一些Utilities方法,辅助其它的类。
package mock.demo;
public class DemoStatic {
public static String sayHello() {
return "Hello";
}
public static String saySomething(String word) {
return word;
}
public static void sayAgain() {
System.out.println(getMyWord());
}
private static String getMyWord() {
return "This is my word";
}
}
我们写一个测试类DemoStaticTest.java, 如下:
@RunWith(PowerMockRunner.class)
@PrepareForTest({DemoStatic.class})
public class DemoStaticTest {
}
注意在类的前面要加这个annotation:
@PrepareForTest({DemoStatic.class})
需要在你的项目中加入下面的maven依赖:
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.4.10</version> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.4.10</version> </dependency>
@Test
public void testMockSayHello() {
PowerMockito.spy(DemoStatic.class);
PowerMockito.when(DemoStatic.sayHello()).thenReturn("my hello");
System.out.println(DemoStatic.sayHello()); // my hello
}
@Test
public void testSaySomething() throws Exception {
PowerMockito.spy(DemoStatic.class);
PowerMockito.when(DemoStatic.class, "saySomething", Mockito.anyString()).thenReturn("something to say!");
System.out.println(DemoStatic.saySomething("say hello")); //something to say!
}
@Test
public void testMockPrivate() throws Exception {
PowerMockito.spy(DemoStatic.class);
PowerMockito.when(DemoStatic.class, "getMyWord").thenReturn("Nothing to say");
DemoStatic.sayAgain(); //Nothing to say
}
问题:静态方法User.convert()的模拟,未匹配到预期值。

Mocking Static Method: // 1.类注解:@PrepareForTest(Static.class) //Static.class 是包含 static methods的类 方法内: // 2.模拟静态类(使用PowerMockito.spy(class)模拟特定方法) PowerMockito.mockStatic(Static.class); // 3.拦截:设置期望值 Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);
检查过程没问题。 直接拦截静态方法试试

验证通过,模拟静态方法没问题。
// 拦截的方法 <E, R> List<R> queryForList(Object var1, Class<E> var2, Function<E, R> var3);
Function类型的参数精确配置不应该 User::convert 这样传。那该怎么传呢?我在官网和百度扒资料,然而不知道是没有,还是没找对。反正,没找到该怎么解决。
没办法,只好先模糊匹配下了

花了时间不一定有收获,不花时间也许也有收获呢。