【发布时间】:2012-08-14 17:18:31
【问题描述】:
说明:
我的 stub 或 mock 似乎无法在我正在测试的课程中生效。我正在尝试使用 whenNew 操作,以便可以模拟返回对象,然后使用返回值模拟对该对象的操作。
我想它是我想念但没有看到的一些简单的东西。
解决方案:最初我使用MockitoRunner.class 运行,需要将其更改为PowerMockRunner.class。下面的代码反映了解决方案。
类路径上的罐子:
- 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;
}
}
【问题讨论】: