spock2.x结合mockito静态mock
作者:互联网
spock2.x开始已经移除了powermock,可以使用mockito-3.4.x之后的版本来解决
mock静态工具类
spock-1.x静态mock使用的是powermock,2.x之后可以结合Mockito-3.4及更新版本一起使用
pom.xml
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>4.3.1</version>
<scope>test</scope>
</dependency>
mocktio静态示例
public class TestUtil {
public static String getName(String name) {
return "hello:" + name;
}
}
junit5单元测试
@BeforeAll
public static void before() {
MockedStatic<TestUtil> mockedStatic = Mockito.mockStatic(TestUtil.class);
}
@Test
@RepeatedTest(value = 3)
public void mockitoTest() {
Mockito.when(TestUtil.getName("张三")).thenReturn("hello张三");
Assertions.assertEquals(TestUtil.getName("张三"), "hello张三");
}
注意: RepeatedTest是重复执行多次,多个相同的静态方法按照官方示例执行一次不会报错,多次就报错了,所以使用Mockito.when().thenReturn()
spock中where示例
@Shared
MockedStatic spring
@Shared
MockedStatic helper
def setupSpec() {
spring = Mockito.mockStatic(SpringContext.class)
helper = Mockito.mockStatic(Helper.class)
}
def check() {
given:"初始化入参"
def queue = new QueueCommon(1, 123)
def queueCheck = new QueueCheck(id: id, auto: false)
and:
queueResultMapper.selectList(1, 123, _, null) >> new ArrayList()
queueMapper.selectList(1, 123, _, null) >> listQueue
queueMapper.updateStatus(*_) >> 1
and:
Mockito.when(Helper.getItem(Constant.QUEUE_STATUS, "0101")).thenReturn(CommonConstant.getItem("0101"));
Mockito.when(Helper.getItem(Constant.QUEUE_STATUS,
"0102")).thenReturn(CommonConstant.getItem("0102"));
Mockito.when(Helper.getItem(Constant.QUEUE_STATUS, "0103")).thenReturn(CommonConstant.getItem("0103"));
Mockito.when(Helper.getItem(Constant.QUEUE_STATUS, "0201")).thenReturn(CommonConstant.getItem("0201"));
Mockito.when(Helper.getItem(Constant.QUEUE_STATUS, "0202")).thenReturn(CommonConstant.getItem("0202"));
expect:
queueServiceImpl.check(queueCommonKey, queueCheck, getOperation(44805379620934L)) == true
where:
idQueue || listQueue | listQueueResult
123|| Arrays.asList(CommonConstant.getQueueById(123)) | Arrays.asList(CommonConstant.getQueueResultById(123))
456|| Arrays.asList(CommonConstant.getQueueById(456)) | Arrays.asList(CommonConstant.getQueueResultById(456))
}
def cleanupSpec() {
spring.close()
helper.close()
}
标签:Mockito,spock2,mockito,when,CommonConstant,getItem,mock,thenReturn 来源: https://www.cnblogs.com/javashare/p/16029609.html