如何从另一个Groovy类调用Spock测试并返回结果?
在Groovy类中调用Spock测试并获取执行结果
一、核心思路
Spock测试基于JUnit框架执行,可通过JUnit的测试启动API调用Spock测试类并收集执行状态;若需获取测试方法内部的业务数据,可通过逻辑抽离或Spock共享变量实现。
二、依赖准备
确保项目包含Spock和JUnit核心依赖(以Gradle为例):
dependencies { testImplementation 'org.spockframework:spock-core:2.3-groovy-4.0' testImplementation 'org.junit.platform:junit-platform-launcher:1.10.0' }
三、调用Spock测试并获取执行状态
通过JUnit 5的Launcher API执行测试,收集成功/失败/跳过等统计结果:
1. 编写Spock测试类
import spock.lang.Specification class MyMathSpec extends Specification { def "验证加法逻辑"() { expect: 1 + 1 == 2 } def "验证失败场景"() { expect: 1 + 1 == 3 } }
2. 编写调用类
import org.junit.platform.engine.discovery.DiscoverySelectors import org.junit.platform.launcher.Launcher import org.junit.platform.launcher.LauncherDiscoveryRequest import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder import org.junit.platform.launcher.core.LauncherFactory import org.junit.platform.launcher.listeners.SummaryGeneratingListener import org.junit.platform.launcher.listeners.TestExecutionSummary class SpockInvoker { static TestExecutionSummary runSpec(Class<?> specClass) { // 构建测试执行请求,指定目标Spock测试类 LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() .selectors(DiscoverySelectors.selectClass(specClass)) .build() // 创建测试启动器和结果监听器 Launcher launcher = LauncherFactory.create() SummaryGeneratingListener listener = new SummaryGeneratingListener() // 执行测试 launcher.execute(request, listener) // 返回执行结果摘要 return listener.summary } static void main(String[] args) { TestExecutionSummary summary = runSpec(MyMathSpec) // 解析并打印结果 println "总测试用例数: ${summary.testsFoundCount}" println "成功数: ${summary.testsSucceededCount}" println "失败数: ${summary.testsFailedCount}" println "跳过数: ${summary.testsSkippedCount}" // 打印失败详情 summary.failures.each { failure -> println "\n失败测试: ${failure.testIdentifier.displayName}" println "错误原因: ${failure.exception.message}" } } }
四、获取测试方法内部的业务数据
方式1:抽离业务逻辑到普通类
将测试中的核心逻辑封装成工具类,测试类和业务类直接调用,避免耦合测试代码:
// 业务逻辑类 class MathUtils { static int add(int a, int b) { return a + b } } // Spock测试类 import spock.lang.Specification class MathUtilsSpec extends Specification { def "验证加法"() { expect: MathUtils.add(1,1) == 2 } } // 其他Groovy类调用 class BusinessService { static void main(String[] args) { def result = MathUtils.add(1,1) println "业务计算结果: ${result}" } }
方式2:使用Spock共享变量
通过@Shared注解定义共享变量,在测试方法中赋值,测试执行后直接读取:
import spock.lang.Shared import spock.lang.Specification class DataCaptureSpec extends Specification { @Shared def testOutputData = null def "生成测试数据"() { given: def data = ["name": "test", "value": 100] expect: data.value == 100 cleanup: testOutputData = data // 将数据存入共享变量 } }
调用测试后读取变量:
// 在SpockInvoker的main方法中添加 runSpec(DataCaptureSpec) println "测试生成的数据: ${DataCaptureSpec.testOutputData}"
内容的提问来源于stack exchange,提问作者sb1234
相关产品推荐
相关产品推荐

