使用PowerMockito模拟Java中其他类的静态函数
我编写了测试类使用PowerMockito模拟Java中其他类的静态函数,java,unit-testing,junit,mockito,powermock,Java,Unit Testing,Junit,Mockito,Powermock,我编写了测试类Main中函数的测试用例,名为functionMain()。我见过有人使用PowerMockito在正在测试的类Main中测试静态函数 但在我的例子中,functionMain()正在使用另一个名为Branch的类中的静态函数,该类名为staticBranchFunction() 我想在Main类的测试中模拟staticBranchFunction() 这个主函数实际上调用了来自不同类的静态函数Branch1,Branch2等 请帮忙 import org.junit.Test;
Main
中函数的测试用例,名为functionMain()
。我见过有人使用PowerMockito在正在测试的类Main
中测试静态函数
但在我的例子中,functionMain()
正在使用另一个名为Branch
的类中的静态函数,该类名为staticBranchFunction()
我想在Main
类的测试中模拟staticBranchFunction()
这个主函数实际上调用了来自不同类的静态函数Branch1
,Branch2
等
请帮忙
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Boom.class})
public class DocTest {
public String boomWrapper() {
return Boom.detonate();
}
@Test
public void testBoom() {
mockStatic(Boom.class);
when(Boom.detonate()).thenReturn("defused");
String actual = boomWrapper();
verifyStatic(Boom.class, times(1));
Boom.detonate();
assertEquals("defused", actual);
}
}
class Boom {
private static final String BOOM = "Boom!";
public static String detonate() {
return BOOM;
}
}
依赖项:
说明:
有关更多受支持的版本,请阅读:,
要求:
- 列出
中的所有静态类,用逗号分隔@PrepareForTest({Boom.class})
- 通过
以逗号分隔模拟所有静态类PowerMockito.mockStatic(Boom.class)
- 使用常规的mockito方法来设置您的期望值,例如
mockito.when(Boom.redemble()).thenReturn(“deflased”)
- 通过
PowerMockito.verifyStatic(Boom.class,Mockito.times(1))验证行为;爆炸代码>重要提示:您需要为每个方法验证调用
PowerMockito.verifyStatic(Boom.class)
更多详细信息。可能的重复实际上回答了如何测试来自同一个被测试类的静态方法,而不是来自不同类的静态函数。您能给我们展示一些代码吗?是的,少量代码将帮助我们理解ClearYou测试/调用junit中的functionMain()吗,它还调用了其他你想模拟的静态方法?
junit:junit:4.12
org.mockito:mockito-core:2.13.0
org.powermock:powermock-module-junit4:2.0.0-beta.5
org.powermock:powermock-api-mockito2:2.0.0-beta.5