gpt4 book ai didi

java - PowerMockito 模拟 whenNew 没有生效

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:26 36 4
gpt4 key购买 nike

描述:

我似乎无法让我的 stub 或模拟在我接受测试的类(class)中生效。我正在尝试使用 whenNew 操作,以便我可以模拟返回对象,然后使用返回值模拟对该对象的操作。

我想象它是一些简单的东西,我错过了但没有看到它。

解决方案:最初我使用 MockitoRunner.class 运行,需要将其更改为 PowerMockRunner.class。下面的代码反射(reflect)了解决方案。

类路径上的 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 功能(@PrepareForTestPowerMockito.whenNew 等),因此您必须使用 PowerMockRunner 运行测试。

@RunWith(PowerMockRunner.class)

因为 ClassB#geResult 不是私有(private)的,你也可以简化你的代码并替换

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

通过

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

关于java - PowerMockito 模拟 whenNew 没有生效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11957485/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com