GraphqlBodyMatcherはWireMockの拡張で、Graphqlのリクエストが意味的に一致しているかを検証します。これは、WireMockのカスタムリクエストマッチャーを利用して実現しています。
空白などの処理に加え、クエリのソートを行い正規化します。
graphqlのパースにはgraphql-java
を利用しています。
また、クエリと同時に変数(variables)も比較します。変数のJsonの比較にはorg.json.JSONObject.similar
を利用しています。ただし、配列の順番は一致していなければなりません。
以下の二つのクエリは一致するとみなされます。
{
hero {
name
friends {
name
age
}
}
}
{
hero {
friends {
age
name
}
name
}
}
以下の二つのクエリは一致しません。
{
hero {
name
friends {
name
age
}
}
}
{
hero {
name
friends {
name
}
}
}
同様に、以下の二つの変数は一致するとみなされます。
(org.json.JsonObject.similar
の挙動に基づきます)
{
"id": 1,
"name": "John Doe"
}
{
"name": "John Doe",
"id": 1
}
しかし、以下の二つの変数は一致しません(配列の順序が異なるため)。
{
"ids": [1, 2, 3]
}
{
"ids": [3, 2, 1]
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'io.github.nilwurtz:wiremock-graphql-extension:0.3.0'
}
<dependency>
<groupId>io.github.nilwurtz</groupId>
<artifactId>wiremock-graphql-extension</artifactId>
<version>0.3.0</version>
<scope>test</scope>
</dependency>
import io.github.nilwurtz.GraphqlBodyMatcher
WireMock.stubFor(
WireMock.post(WireMock.urlEqualTo("/graphql"))
.andMatching(GraphqlBodyMatcher.withRequestJson("""{"query": "{ hero { name }}"}"""))
.willReturn(WireMock.ok())
)
Jsonボディ内 query
キーにGraphQLクエリが存在することを期待しています。
変数がある場合、Jsonボディ内 variables
キーに変数が存在することを期待しています。
val expectedQuery = """
query HeroInfo($id: Int) {
hero(id: $id) {
name
}
}
""".trimIndent()
val expectedVariables = """
{
"id": 1
}
""".trimIndent()
val expectedJson = """
{
"query": "$expectedQuery",
"variables": $expectedVariables
}
""".trimIndent()
WireMock.stubFor(
WireMock.post(WireMock.urlEqualTo("/graphql"))
.andMatching(GraphqlBodyMatcher.withRequestJson(expectedJson))
.willReturn(WireMock.ok())
)
withRequestQueryAndVariables
メソッドも利用できます。
import io.github.nilwurtz.GraphqlBodyMatcher
WireMock.stubFor(
WireMock.post(WireMock.urlEqualTo("/graphql"))
.andMatching(GraphqlBodyMatcher.withRequestQueryAndVariables("{ hero { name }}"))
.willReturn(WireMock.ok())
)
val expectedQuery = """
query HeroInfo($id: Int) {
hero(id: $id) {
name
}
}
""".trimIndent()
val expectedVariables = """
{
"id": 1
}
""".trimIndent()
WireMock.stubFor(
WireMock.post(WireMock.urlEqualTo("/graphql"))
.andMatching(GraphqlBodyMatcher.withRequestQueryAndVariables(expectedQuery, expectedVariables))
.willReturn(WireMock.ok())
)
現段階ではメジャーリリース前で、Queryの一部分をサポートしており、ミューテーションやエイリアスなどの全ての機能は網羅していません。将来的にはこれらの機能もサポートする予定です。
This project is licensed under the terms of the MIT License.
Contributions are welcome! Feel free to open an issue or submit a pull request if you have any improvements or suggestions.