Spring Cloud Contract集成测试WireMock请求匹配失败排查
Let's break down why you're hitting this matching error and fix it step by step.
Key Issues Identified
Looking at your request details, contract code, and test code, there are two critical mismatches causing the failure:
1. Request Path Mismatch
- Actual Request URL:
/my-project/api/checkTransaction/id?id=ASDFGHJKL(includes the/my-projectcontext path) - Contract Defined URL:
/api/checkTransaction/id(no context path) - Test Code Request Path:
/api/id/ASDFGHJKL/check(completely different from the contract's path)
WireMock uses exact path matching by default, so even a missing or extra prefix like /my-project will break the match. Plus, your test is sending a request to a totally different endpoint than what the contract defines—this is a major contributor to the failure.
2. Irrelevant Headers (X-B3 etc.)
You don't need to add X-B3-ParentSpanId or other Zipkin trace headers to your contract. Spring Cloud Contract and WireMock only validate the headers explicitly defined in your contract; extra headers in the request are ignored by default. Removing the username header didn't fix the issue because the problem wasn't with header validation.
Fixes to Apply
Follow these steps to resolve the matching error:
Step 1: Align Test Code with Contract Path
Update your test's request path to match exactly what's in the contract. Change this line:
.get("/api/id/ASDFGHJKL/check");
To:
.get("/api/checkTransaction/id");
Step 2: Handle the /my-project Context Path
You have two options here, pick the one that fits your setup:
- Option A: Update the Contract URL
Modify the contract'surlto include the context path:url('/my-project/api/checkTransaction/id') { // rest of the contract details } - Option B: Configure WireMock to Use the Context Path
Add this property to your test'sapplication.propertiesorapplication.yml:
This tells WireMock to expect requests with thespring.cloud.contract.wiremock.server.context-path=/my-project/my-projectprefix, so your existing contract URL will work without changes.
Step 3: Add Missing Required Header
Your contract requires a defaultId header with value 12345, but your test code doesn't set this. Add it to your request specification:
MockMvcRequestSpecification request = given() .header("requestKey", "RANDOM") .header("defaultId", "12345") // Add this line .header("accept-language", "en") .header("accept-encoding", "gzip") .header("Content-Type", "application/json;charset=UTF-8");
Final Checks
After applying these fixes, run your test again. The request should now match the WireMock stub defined by your Spring Cloud Contract, and you'll no longer see the "Request was not matched" error.
内容的提问来源于stack exchange,提问作者greenthunder

