How to mock static method without powermock(如何在没有 powermock 的情况下模拟静态方法)
问题描述
在 JUnit 中进行测试时,有什么方法可以模拟静态 util 方法吗?
Is there any way we can mock the static util method while testing in JUnit?
我知道 Powermock 可以模拟静态调用,但我不想使用 Powermock.
I know Powermock can mock static calls, but I don't want to use Powermock.
还有其他选择吗?
推荐答案
(不过我假设你可以使用 Mockito)我没有想到任何专门的东西,但是当涉及到这样的情况时,我倾向于使用以下策略:
(I assume you can use Mockito though) Nothing dedicated comes to my mind but I tend to use the following strategy when it comes to situations like that:
1) 在被测类中,将静态直接调用替换为对封装静态调用本身的包级方法的调用:
1) In the class under test, replace the static direct call with a call to a package level method that wraps the static call itself:
public class ToBeTested{
public void myMethodToTest(){
...
String s = makeStaticWrappedCall();
...
}
String makeStaticWrappedCall(){
return Util.staticMethodCall();
}
}
2) 在测试和模拟封装的包级方法时监视被测类:
2) Spy the class under test while testing and mock the wrapped package level method:
public class ToBeTestedTest{
@Spy
ToBeTested tbTestedSpy = new ToBeTested();
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void myMethodToTestTest() throws Exception{
// Arrange
doReturn("Expected String").when(tbTestedSpy).makeStaticWrappedCall();
// Act
tbTestedSpy.myMethodToTest();
}
}
这是我写的一篇关于间谍的文章,其中包括类似的案例,如果您需要更多见解:sourceartists.com/mockito-spying
Here is an article I wrote on spying that includes similar case, if you need more insight: sourceartists.com/mockito-spying
这篇关于如何在没有 powermock 的情况下模拟静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在没有 powermock 的情况下模拟静态方法


基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01