PowerMock,模拟静态方法,然后在所有其他静态上调用真实方法

编程入门 行业动态 更新时间:2024-10-28 00:27:18
本文介绍了PowerMock,模拟静态方法,然后在所有其他静态上调用真实方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在设置模拟类的静态方法。我必须在 @Before -annotated JUnit设置方法中执行此操作。

I'm setting up mocking a class' static methods. I have to do this in a @Before-annotated JUnit setup method.

我的目标是设置类为我明确模拟的那些方法调用真正的方法,除。

My goal is to setup the class to call real methods, except for those methods I explicitly mock.

基本上:

@Before public void setupStaticUtil() { PowerMockito.mockStatic(StaticUtilClass.class); when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5); // mock out certain methods... // Now have all OTHER methods call the real implmentation??? How do I do this? }

我遇到的问题是 StaticUtilClass 方法 public static int someStaticMethod(String s)很遗憾地抛出一个 RuntimeException 如果提供的话使用 null 值。

The problem I'm running into is that within StaticUtilClass the method public static int someStaticMethod(String s) unfortunately throws a RuntimeException if supplied with a null value.

所以我不能简单地将调用实际方法的明显路线作为默认值回答如下:

So I can't simply go the obvious route of calling real methods as the default answer as below:

@Before public void setupStaticUtil() { PowerMockito.mockStatic(StaticUtilClass.class, CALLS_REAL_METHODS); // Default to calling real static methods // The below call to someStaticMethod() will throw a RuntimeException, as the arg is null! // Even though I don't actually want to call the method, I just want to setup a mock result when(StaticUtilClass.someStaticMethod(antString())).thenReturn(5); }

我需要设置默认的Answer来调用所有其他静态方法的实方法之后我模拟了我对模拟感兴趣的方法的结果。

I need to set the default Answer to call real methods on all other static methods after I mock the results from the method I'm interested in mocking.

这可能吗?

推荐答案

你在寻找什么称为部分嘲笑。

在PowerMock中,您可以使用 mockStaticPartial 方法。

In PowerMock you can use mockStaticPartial method.

在PowerMockito中,您可以使用存根,这将只存根方法定义并保留其他不变:

In PowerMockito you can use stubbing, which will stub only the method defined and leave other unchanged:

PowerMockito.stub(PowerMockito.method(StaticUtilClass.class, "someStaticMethod")).toReturn(5);

也不要忘记

@PrepareForTest(StaticUtilClass.class)

更多推荐

PowerMock,模拟静态方法,然后在所有其他静态上调用真实方法

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

发布评论

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

>www.elefans.com

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