当前位置: 首页 > 工具软件 > Spock > 使用案例 >

springboot +spock

西门建安
2023-12-01

springboot使用spock做单测

静态方法mock: PowerMockito

需要注意只配置@PrepareForTest和RunWith是不生效的,这样会爆方法找不到的java异常, 原因是spock本身就有@RunWith(Sputnik.class)

@PrepareForTest({ StaticClassYouWantTest.class})
@RunWith(PowerMockRunner.class)

需要改成

@PrepareForTest({ StaticClassYouWantTest.class})
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Sputnik.class)

使用时

PowerMockito.mockStatic(StaticClassYouWantTest.class)
Mockito.when(StaticClassYouWantTest.methodA()).thenReturn(true)

PrepareForTest使用时机

1. PowerMockito.whenNew

必须加注解@PrepareForTest和@RunWith。
注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。

2. mock final

必须加注解@PrepareForTest和@RunWith。
注解@PrepareForTest里写的类是final方法所在的类。

3. mock 静态方法

必须加注解@PrepareForTest和@RunWith。
注解@PrepareForTest里写的类是静态方法所在的类。

4. mock私有方法

只需要加注解@PrepareForTest
注解里写的类是私有方法所在的类

5. mock系统类的静态方法

必须加注解@PrepareForTest和@RunWith。
注解里写的类是需要调用系统方法所在的类

ref :

https://blog.csdn.net/qaz296490709/article/details/72880370

 类似资料: