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

PowerMock, mock a static method, THEN call real methods on all other statics(PowerMock,模拟一个静态方法,然后在所有其他静态上调用真实方法)
本文介绍了PowerMock,模拟一个静态方法,然后在所有其他静态上调用真实方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在设置模拟类的静态方法.我必须在 @Before 注释的 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);

  // mock out certain methods...
  when(StaticUtilClass.someStaticMethod(anyString())).thenReturn(5); 

  // Now have all OTHER methods call the real implementation???  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); 
}

我需要设置默认答案以在所有其他静态方法上调用真实方法之后我模拟了我感兴趣的方法的结果.

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.

这可能吗?

推荐答案

你在找什么叫做partial 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,模拟一个静态方法,然后在所有其他静态上调用真实方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)