Spring Boot 集成 Spock

一篇 Spock 入门 介绍了 Spock 基础概念。本篇主要介绍 Spring Boot 使用 Gradle 集成 Spock。

环境:

  • java11
  • gradle-6.6.1

build.gradle

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
plugins {
	id 'org.springframework.boot' version '2.4.2'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
	id 'groovy'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
	maven {
		url "http://maven.aliyun.com/nexus/content/groups/public/"
	}
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
//	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	implementation 'org.codehaus.groovy:groovy:3.0.5'
	testImplementation('org.spockframework:spock-core:2.0-M3-groovy-3.0')
	testImplementation('org.spockframework:spock-spring:2.0-M3-groovy-3.0')
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

注意:

IDEA 对 Groovy 测试项目,默认识别路径为:src/test/groovy

路径配置错误,会找不到单测方法,报:no tests found for given includes

新建测试类 HelloUtilsTest ,验证 Spock 是否可以正常使用。

1
2
3
4
5
6
class HelloUtilsTest extends Specification {
    def "test" () {
        expect:
        assert "hello".length() == 5
    }
}

验证 @SpringBootTest

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = DemoApplication)
class HelloUtilsTest extends Specification {
    @Autowired
    HelloUtils helloUtils;

    def "say" () {
        expect:
        assert "say hello".equals(helloUtils.say())
    }
}

helloUtils.java

1
2
3
4
5
6
@Component
public class HelloUtils {
    public String say() {
        return "say hello";
    }
}

以上为 Gradle 集成 Spock 方法,Maven 方式可以看看:https://www.baeldung.com/spring-spock-testing

updatedupdated2021-02-082021-02-08
Load Comments?