使用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对象代码所在的类。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2018-01-05 Cannot change version of project facet Dynamic Web Module to 3.0 requires Java 1.6 or newer 解决方案
2018-01-05 mysql 子查询