spock是基于groovy语言的,相比于junit可以省略不少代码,但是静态mock就相对麻烦点了
spock-1.x的静态方法mock
spock-1.x中静态mock我们可以结合powermock来实现,美团spock
spock-2.x中使用mockito
为什么spock-2.x中使用mockito而不是使用powermock是因为官方移除了组件,spock官网
spock-2.x结合mockito测试静态方法
pom.xml
<properties>
<project.compiler.sourceEncoding>UTF-8</project.compiler.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>2.0-groovy-3.0</version>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>2.0-groovy-3.0</version>
</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.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.6.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.4</version>
</plugin>
</plugins>
</build>
FileSpec.groovy
class FileSpec extends Specification {
def mockDemo = new MockDemo()
def fileTest() {
given:
MockedStatic fileUtil = Mockito.mockStatic(FileUtil.class)
fileUtil.when(FileUtil::parseFile("D:/hello.java")).thenReturn("hello")
expect:
mockDemo.getFileContent("D:/hello.java") == "hello"
}
}
FileUtil.java
public class FileUtil {
public static String parseFile(String path) {
return "";
}
}
MockDemo.java
public class MockDemo {
public String getFileContent(String path) {
return FileUtil.parseFile(path);
}
}
验证
遇到的坑
mockito-inline在idea中显示has broken path
,修改pom版本号即可,如果mockito-inline没有加载,则idea左侧external library
将不会显示会报错
does not support the creation of static mocks
Mockito's inline mock maker supports static mocks based on the Instrumentation API.", "You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.", "Note that Mockito's inline mock maker is not supported on Android.
参考
美团spock
老K的博客
spock官网
mockito官网