如何在没有 powermock 的情况下模拟静态方法

编程入门 行业动态 更新时间:2024-10-27 20:30:01
本文介绍了如何在没有 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/mockito-spying

Here is an article I wrote on spying that includes similar case, if you need more insight: sourceartists/mockito-spying

更多推荐

如何在没有 powermock 的情况下模拟静态方法

本文发布于:2023-10-31 03:52:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   情况下   方法   如何在   powermock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!