环境

  • 🍎Gradle
  • 🍊Spring Boot 2.3.6.RELEASE
  • 🍍Java 8
  • 🥒Groovy 3.0.6
  • 🥥Spock 2.0-M4-groovy-3.0
  • 🍑guava 30.0-jre

布局

image.png

父项目:parent

build.gradle

  1. ext {//版本变量
  2. guavaVersion = "30.0-jre"
  3. spockVersion = "2.0-M4-groovy-3.0"
  4. groovyVersion = "3.0.6"
  5. }
  6. //所有项目通用配置
  7. allprojects {
  8. apply plugin: 'java'
  9. group = 'com.lugew.example-springboot-spock'
  10. version = '0.0.1-SNAPSHOT'
  11. sourceCompatibility = '1.8'//源码指定Java 8
  12. targetCompatibility = '1.8'
  13. //仓库
  14. repositories {
  15. mavenLocal()//本地优先级最高
  16. maven {//阿里云
  17. name '阿里云'
  18. url 'https://maven.aliyun.com/repository/public/'
  19. }
  20. mavenCentral()//中央仓库
  21. google()//google仓库
  22. }
  23. test {//使用JUnit测试平台
  24. useJUnitPlatform()
  25. }
  26. }
  27. //子项目通用配置
  28. subprojects {
  29. dependencies {
  30. implementation "com.google.guava:guava:${guavaVersion}"//guava
  31. testImplementation "org.codehaus.groovy:groovy-all:${groovyVersion}"//groovy
  32. testImplementation "org.codehaus.groovy:groovy:${groovyVersion}"//groovy
  33. testImplementation "org.spockframework:spock-core:${spockVersion}"//spock
  34. }
  35. }

setting.gradle

rootProject.name = 'parent'//父项目名称
includeFlat 'son'//平级子项目

子项目:son

build.gradle

plugins {
    id 'org.springframework.boot' version '2.3.6.RELEASE'//springboot 插件
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'//springboot 依赖插件
    id 'groovy'//groovy插件
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'//spring-boot-starter
    implementation 'org.springframework.boot:spring-boot-starter-web'//web

    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

setting.gradle

rootProject.name = 'son'

源码

image.png

groovy

Spock测试代码所在位置

java

JUnit测试代码所在位置

例子

JUnit

以加法器Adder为例:

package com.lugew.examplespringbootspock.son.adder;

/**
 * 加法
 *
 * @author LuGew
 * @since 2020/12/8
 */
public class Adder {

    public double add(double a, double b) {//加法
        return a + b;
    }

}

测试

AdderSpec

package com.lugew.examplespringbootspock.son.adder

import spock.lang.Specification

/**
 * @author LuGew*
 * @since 2020/12/8
 */
class AdderSpec extends Specification {
    def "加法返回正确值 #a+#b=#c"() {
        given: "初始化加法器"
        Adder adder = new Adder()
        expect: "返回正确值"
        adder.add(a, b) == c
        where: "例子"
        a | b  || c
        1 | 1  || 2
        2 | 1  || 3
        2 | 0  || 2
        0 | 0  || 0
        1 | -1 || 0
    }
}

输出:
image.png

Spring