LoginSignup
9
14

More than 5 years have passed since last update.

MockMvcを使ったControllerのUnitTestでJsonのRequest

Last updated at Posted at 2016-12-21

概要

SpringのMockMvcを使ってControllerのテストで、JsonRequestする。

前提

  • Spring Boot を使用する。
  • モデルでは日付型に JSR310 (LocalDate、他) を使用する。

テスト対象メソッド

@PostMapping(value = "hoge", consumes = MediaType.APPLICATION_JSON_VALUE)
public void hoge(@RequestBody Hoge hoge) {
    System.out.println("hoge");
}

Jackson を依存に追加

JavaとJsonの変換にはJacksonを利用する。
下記はMavenの例。

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.6.1</version>
</dependency>

UnitテストでJsonのリクエスト

下記はSpockでの例。

def "JsonのPostリクエスト"() {
    setup:
    // JacksonでオブジェクトをJson形式に変換
    def hoge = new Hoge();
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(hoge);

    expect:
    mockMvc.perform(MockMvcRequestBuilders
        .post('/hoge')
        // ContentTypeの設定
        .contentType(MediaType.APPLICATION_JSON)
        // Jsonの設定
        .content(json)
    ).andExpect(
        MockMvcResultMatchers.status().is(HttpStatus.OK.value()),
    )
}

参考

9
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
14