Python 官方文档:入门教程 => 点击学习
PowerMockito 测试静态方法 假如有下面一个类DemoStatic,它里面定义了各种静态方法,这些静态方法可能是一些Utilities方法,辅助其它的类。 packag
假如有下面一个类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})
<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 这样传。那该怎么传呢?我在官网和百度扒资料,然而不知道是没有,还是没找对。反正,没找到该怎么解决。
没办法,只好先模糊匹配下了
花了时间不一定有收获,不花时间也许也有收获呢。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: 怎样使用PowerMockito 测试静态方法
本文链接: https://www.lsjlt.com/news/130299.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0