技巧
Mock 静态方法
GroovyMock 也可以 mock 静态方法,但其只能 mock 由 Groovy 编写的静态方法,不能对 Java 编写的静态方法进行 mock,需要使用其他方法进行 mock。
spock-1.x 版本中 mock 静态方法使用 powermock,而在 2.x 中需要使用 Mockito-3.4[1]。
mockito 需要依赖以下 jar:
org.mockito:mockito-core:4.3.1
org.mockito:mockito-inline:4.3.1
使用方法:
class StudentTest extends Specification {
Mockito.mockStatic(IDGenerator.class)
def "should success when create student"() {
given:
var name = "tester"
var code = "123456"
Mockito.when(IDGenerator.nextId()).thenReturn("123456789")
when:
var student = Student.create(name, code)
then:
student.getId() == "123456789"
}
}
class StudentTest extends Specification {
MockedStatic<IDGenerator> generator
def setup() {
generator = Mockit.mockStatic(IDGenerator.class)
}
// The test case
def cleanup() {
// eliminate Mock Static method of
generator.close()
}
}
Maven 工程
pom.xml 依赖以下内容:
<properties>
<spock.version>2.1-groovy-3.0</spock.version>
<byte-buddy.version>1.12.9</byte-buddy.version>
<mockito.version>4.3.1</mockito.version>
<logback.version>1.2.11</logback.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-bom</artifactId>
<version>${spock.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- test -->
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>${byte-buddy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 这个不加的话无法执行单元测试类 -->
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.13.1</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
<configuration>
<testSources>
<testSource>
<directory>${project.basedir}/src/test/groovy</directory>
<includes>
<include>**/*.groovy</include>
</includes>
</testSource>
</testSources>
</configuration>
</plugin>