java PowerMockito Mocking whenNew 不生效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11957485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerMockito Mocking whenNew not taking effect
提问by haju
Description:
描述:
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.
我似乎无法让我的存根或模拟在我接受测试的课程中生效。我正在尝试使用 whenNew 操作,以便我可以模拟返回对象,然后使用返回值模拟对该对象的操作。
I imagine its something simple I am missing but not seeing it.
我想象它的一些简单的东西我想念但没有看到它。
SOLUTION: Originally I was running with MockitoRunner.class
and it required being changed to PowerMockRunner.class
. Code below reflects the solution.
解决方案:最初我正在运行,MockitoRunner.class
它需要更改为PowerMockRunner.class
. 下面的代码反映了解决方案。
Jars on the classpath:
类路径上的罐子:
- 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
TEST CLASS
测试班
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);
}
}
Class A Implementation
A类实现
public class ClassA implements IClassA {
@Override
public String[] runTest(String[] inputValues) {
String[] result;
IClassB classB = new ClassB();
result = classB.getResult(inputValues);
return result;
}
}
回答by gontard
Since you are using powermock features (@PrepareForTest
, PowerMockito.whenNew
etc.), you have to run your test with the PowerMockRunner.
由于使用powermock功能(@PrepareForTest
,PowerMockito.whenNew
等等),你必须运行与PowerMockRunner测试。
@RunWith(PowerMockRunner.class)
Because ClassB#geResult is not private, you may also simplify your code and replace
因为 ClassB#geResult 不是私有的,你也可以简化你的代码并替换
when( mockedClassB, "getResult", any(String[].class) ).thenReturn(someValue);
by
经过
when(mockedClassB.getResult(any(String[].class))).thenReturn(someValue);