You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pact/JUnit5进行契约验证测试时遭遇‘At least one pact source must be present on the test class’错误求助

解决Pact/JUnit5契约测试中"At least one pact source must be present"错误

从你的错误日志来看,核心问题是Pact无法识别到有效的契约源(日志里显示Pact source on test class: null和Pact loaders on test class: []),结合你使用的Pact 4.1.7版本,我整理了几个针对性的解决方案:

1. 确认依赖完整性

首先要确保你已经正确引入了Pact JUnit5的提供端依赖,这是注解能被识别的基础:

Maven依赖

<dependency>
    <groupId>au.com.dius.pact.provider</groupId>
    <artifactId>junit5</artifactId>
    <version>4.1.7</version>
    <scope>test</scope>
</dependency>

Gradle依赖

testImplementation 'au.com.dius.pact.provider:junit5:4.1.7'

如果之前只引入了Pact的核心包,缺少这个JUnit5适配器,@PactFolder等注解就无法被框架扫描到。

2. 检查注解的包导入

确保你的@PactFolder注解是来自Pact JUnit5的专用包,而不是JUnit4版本的:

// 正确的导入
import au.com.dius.pact.provider.junit5.PactFolder;

如果导入了au.com.dius.pact.provider.junit.PactFolder(JUnit4的包),在JUnit5环境下会完全失效。

3. 验证契约文件的路径与命名

你指定了@PactFolder("pacts"),对应的路径是src/test/resources/pacts,需要满足两个条件:

  • 该目录下确实存在契约文件(格式为.json)
  • 文件名符合Pact的命名规范:[consumer-name]-[provider-name].json,比如你的提供者是myAwesomeService,文件名应该类似myConsumer-myAwesomeService.json

如果文件名不匹配,Pact也无法识别到对应的契约。

修正后的完整示例代码

这里是导入正确、配置齐全的测试类代码:

import au.com.dius.pact.provider.junit5.PactFolder;
import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import au.com.dius.pact.provider.junit5.Provider;
import au.com.dius.pact.provider.junit5.target.MockMvcTestTarget;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@Provider("myAwesomeService")
@PactFolder("pacts")
class MockMvcTestTargetStandaloneMockMvcTestJava {

    @BeforeEach
    void before(PactVerificationContext context) {
        MockMvcTestTarget testTarget = new MockMvcTestTarget();
        testTarget.setControllers(new DataResource());
        context.setTarget(testTarget);
    }

    @RestController
    static class DataResource {
        @GetMapping("/data")
        @ResponseStatus(HttpStatus.NO_CONTENT)
        void getData(@RequestParam("ticketId") String ticketId) {
        }
    }

    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void pactVerificationTestTemplate(PactVerificationContext context) {
        context.verifyInteraction();
    }
}

按照以上步骤排查后,应该就能解决契约源找不到的问题了。

内容的提问来源于stack exchange,提问作者drone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:48:30