MockMvc と JsonPath を使用して、Spring HATEOAS バックエンドの単体テストを作成しています。応答に含まれるリンクをテストするには、次のようなことをしています。
@Test
public void testListEmpty() throws Exception {
mockMvc.perform(get("/rest/customers"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.links", hasSize(1))) // make sure links only contains self link
.andExpect(jsonPath("$.links[?(@.rel=='self')]", hasSize(1))) // make sure the self link exists 1 time
.andExpect(jsonPath("$.links[?(@.rel=='self')].href", contains("http://localhost/rest/customers{?page,size,sort}"))) // test self link is correct
.andExpect(jsonPath("$.links[?(@.rel=='self')][0].href", is("http://localhost/rest/customers{?page,size,sort}"))) // alternative to test self link is correct
.andExpect(jsonPath("$.content", hasSize(0))); // make sure no content elements exists
}
ただし、自分で簡単にするために使用すべきベストプラクティスがいくつかあるのではないかと思います。
- リンクの内容をテストするの
http://localhost
は適切ではありません。Spring MovkMvc ヘルパーを使用してホストを特定できますか? - JsonPath では、2 つの属性が特定の値を持つ要素が配列に含まれているかどうかをテストするのは困難です。そのように、配列には特定の値を持つ自己リンクが含まれている必要があります。上記をテストするためのより良い方法はありますか? これは、エラー メッセージのあるフィールドの検証エラーをテストするときにも役立ちます。
私はいくつかのブログ投稿で以下のようなテクニックを見てきました:
.andExpect(jsonPath("$.fieldErrors[*].path", containsInAnyOrder("title", "description")))
.andExpect(jsonPath("$.fieldErrors[*].message", containsInAnyOrder(
"The maximum length of the description is 500 characters.",
"The maximum length of the title is 100 characters.")));
ただし、これはタイトルに特定のエラー メッセージがあることを保証するものではありません。また、タイトルの「説明の最大長は 500 文字です」が間違っている可能性もあります。しかし、テストは成功します。