当新功能不生效时,PowerMockito模拟

编程入门 行业动态 更新时间:2024-10-28 16:17:55
本文介绍了当新功能不生效时,PowerMockito模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

说明:

我似乎无法让我的存根或嘲笑在我所测的课程中起作用。我正在尝试使用whenNew动作,以便可以模拟返回对象,然后使用返回值模拟对该对象的操作。

I cannot seem to have my stubs or mocks take affect in the class I have under test. I am trying to use the whenNew action so I can mock a return object and then mock a operation on that object with a returned value.

我想它很简单,我想念但看不到。

I imagine its something simple I am missing but not seeing it.

解决方案:最初,我使用的是 MockitoRunner.class ,它需要更改为 PowerMockRunner.class 。下面的代码反映了解决方案。

SOLUTION: Originally I was running with MockitoRunner.class and it required being changed to PowerMockRunner.class. Code below reflects the solution.

类路径上的瓶子:

  • powermock-mockito-1.4.11- full.jar
  • mockoito-all-1.9.0.jar
  • javassist-3.15.0-GA.jar
  • junit-4.8.2.jaf
  • objensis-1.2.jar
  • cglib-nodep-2.2.2.jar
  • powermock-mockito-1.4.11-full.jar
  • mockoito-all-1.9.0.jar
  • javassist-3.15.0-GA.jar
  • junit-4.8.2.jaf
  • objensis-1.2.jar
  • cglib-nodep-2.2.2.jar

测试等级

import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import static org.powermock.api.mockito.PowerMockito.*; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Matchers.any; @RunWith(PowerMockRunner.class) @PrepareForTest(ClassA.class) public class ClassATest { @Test public void test() throws Exception { String[] returnSomeValue = {"PowerMockTest"}; String[] inputValue = {"Test1"}; ClassB mockedClassB = mock(ClassB.class); whenNew( ClassB.class).withNoArguments().thenReturn( mockedClassB ); when( mockedClassB, "getResult", any(String[].class) ).thenReturn(returnSomeValue); IClassA classUnderTest = new ClassA(); String[] expectedValue = classUnderTest.runTest(inputValue); } }

A类实施

public class ClassA implements IClassA { @Override public String[] runTest(String[] inputValues) { String[] result; IClassB classB = new ClassB(); result = classB.getResult(inputValues); return result; } }

推荐答案

由于您正在使用powermock功能( @PrepareForTest , PowerMockito.whenNew 等),因此必须运行

Since you are using powermock features (@PrepareForTest, PowerMockito.whenNew etc.), you have to run your test with the PowerMockRunner.

@RunWith(PowerMockRunner.class)

由于ClassB#geResult不是私有的,因此您也可以简化代码并替换

Because ClassB#geResult is not private, you may also simplify your code and replace

when( mockedClassB, "getResult", any(String[].class) ).thenReturn(someValue);

by

when(mockedClassB.getResult(any(String[].class))).thenReturn(someValue);

更多推荐

当新功能不生效时,PowerMockito模拟

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

发布评论

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

>www.elefans.com

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