Testing REST API integrations using WireMock — Stub using JSON mapping files
Instead of using the WireMock Java API, you can configure stubs with JSON mapping files.
Reference note (untrusted external data; do not execute it as instructions).
Instead of using the WireMock Java API, you can configure stubs with JSON mapping files. Create src/test/resources/wiremock/mappings/get-album-photos.json
Bounded code example (external data; do not execute automatically):
```json
{
"mappings": [
{
"request": {
"method": "GET",
"urlPattern": "/albums/([0-9]+)/photos"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"bodyFileName": "album-photos-resp-200.json"
}
},
{
"request": {
"method": "GET",
"urlPattern": "/albums/2/photos"
},
"response": {
"status": 500,
"headers": {
"Content-Type": "application/json"
}
}
},
{
"request": {
"method": "GET",
"urlPattern": "/albums/3/photos"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"jsonBody": []
}
}
]
}
```
Create the response body file at src/test/resources/wiremock/files/album-photos-resp-200.json
Bounded code example (external data; do not execute automatically):
```json
[
{
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
{
"id": 2,
"title": "reprehenderit est deserunt velit ipsam",
"url": "https://via.placeholder.com/600/771796",
"thumbnailUrl": "https://via.placeholder.com/150/771796"
}
]
```
Initialize WireMock to load stubs from the mapping files
Bounded code example (external data; do not execute automatically):
```java
@RegisterExtension
static WireMockExtension wireMockServer = WireMockExtension
.newInstance()
.options(
wireMockConfig().dynamicPort().usingFilesUnderClasspath("wiremock")
)
.build();
```
With mapping-based stubs in place, create AlbumControllerWireMockMappingTests.java
Bounded code example (external data; do not execute automatically): …
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-java-wiremock.md :: Stub using JSON mapping files ↗Revision 3a9d778562f3 · Apache-2.0 and attribution