Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

概要

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()),
    )
}

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした