使用PowerMockito.whennew的时候,注解preparefortest里面的类需要是mock的new代码所在的类的对象
Mock方法内部new出来的对象
测试目标代码:
01
public class ClassUnderTest {
02
03
public boolean callInternalInstance(String path) {
04
05
File file = new File(path);
06
07
return file.exists();
08
09
}
10
}
测试用例代码:
01
@RunWith(PowerMockRunner.class)
02
public class TestClassUnderTest {
03
04
@Test
05
@PrepareForTest(ClassUnderTest.class)
06
public void testCallInternalInstance() throws Exception {
07
08
File file = PowerMockito.mock(File.class);
09
10
ClassUnderTest underTest = new ClassUnderTest();
11
12
PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file);
13
14
PowerMockito.when(file.exists()).thenReturn(true);
15
16
Assert.assertTrue(underTest.callInternalInstance("bbb"));
17
}
18
}
说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。
Mock方法内部new出来的对象
测试目标代码:
01 |
public class ClassUnderTest { |
02 |
03 |
public boolean callInternalInstance(String path) { |
04 |
05 |
File file = new File(path); |
06 |
07 |
return file.exists(); |
08 |
09 |
} |
10 |
} |
测试用例代码:
01 |
@RunWith (PowerMockRunner. class ) |
02 |
public class TestClassUnderTest { |
03 |
04 |
@Test |
05 |
@PrepareForTest (ClassUnderTest. class ) |
06 |
public void testCallInternalInstance() throws Exception { |
07 |
08 |
File file = PowerMockito.mock(File. class ); |
09 |
10 |
ClassUnderTest underTest = new ClassUnderTest(); |
11 |
12 |
PowerMockito.whenNew(File. class ).withArguments( "bbb" ).thenReturn(file); |
13 |
|
14 |
PowerMockito.when(file.exists()).thenReturn( true ); |
15 |
16 |
Assert.assertTrue(underTest.callInternalInstance( "bbb" )); |
17 |
} |
18 |
} |
说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。