使用 PowerMockito.whenNew() 不会被嘲笑,而是调用原始方法

Using PowerMockito.whenNew() is not getting mocked and original method is called(使用 PowerMockito.whenNew() 不会被嘲笑,而是调用原始方法)
本文介绍了使用 PowerMockito.whenNew() 不会被嘲笑,而是调用原始方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个类似下面的代码:

I have a code somewhat like this below:

Class A {
  public boolean myMethod(someargs) {
    MyQueryClass query = new MyQueryClass();
    Long id = query.getNextId();
    // some more code
  }
}
Class MyQueryClass     {
  ....
  public Long getNextId() {
    //lot of DB code, execute some DB query
    return id;
  }
}

现在我正在为 A.myMethod(someargs) 编写测试.我想跳过真正的方法 query.getNextId() 而是返回一个存根值.基本上,我想模拟 MyQueryClass.

Now I'am writing a test for A.myMethod(someargs). I want to skip the real method query.getNextId() and instead return a stub value. Basically, I want to mock MyQueryClass.

所以在我的测试用例中,我使用了:

So in my test case, I have used:

MyQueryClass query = PowerMockito.mock(MyQueryClass.class);
PowerMockito.whenNew(MyQueryClass.class).withNoArguments().thenReturn(query);
when(query.getNextId()).thenReturn(1000000L);

boolean b = A.getInstance().myMethod(args);

//asserts

我在测试类的开头使用了 @RunWith(PowerMockRunner.class)@PrepareForTest({MyQueryClass.class}).

I used @RunWith(PowerMockRunner.class) and @PrepareForTest({MyQueryClass.class}) in the beginning of my test class.

但是我调试测试的时候,还是调用了MyQueryClass类的真实方法getNextId().

But when I debug the test, it is still calling the real method getNextId() of the MyQueryClass class.

我在这里缺少什么?任何人都可以提供帮助,因为我是 Mockito 和 PowerMockito 的新手.

What am I missing here? Can anyone help as I am new to Mockito and PowerMockito.

推荐答案

需要将调用构造函数的类放到@PrepareForTest注解中,而不是正在构造的类 - 请参阅 模拟新对象的构造.

You need to put the class where the constructor is called into the @PrepareForTest annotation instead of the class which is being constructed - see Mock construction of new objects.

在你的情况下:

@PrepareForTest(MyQueryClass.class)

@PrepareForTest(A.class)

更笼统的:

@PrepareForTest(NewInstanceClass.class)

@PrepareForTest(ClassThatCreatesTheNewInstance.class)

这篇关于使用 PowerMockito.whenNew() 不会被嘲笑,而是调用原始方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

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 - 获取键盘按键)