LoginSignup
12
18

More than 5 years have passed since last update.

MockRestServiceServerで色んなメソッドテスト

Posted at

MockRestServiceServerとは

ここにはexample的にコードを書き残しておきます。

MockRestServiceServer を使うことで呼び出されるはずのURL、リクエスト内容、ヘッダ、メソッドを設定する事が可能です。
正しく呼出しが行われなかった場合、java.lang.AssertionError となります。

MockRestServiceServer.createServer で作成し、andExpect を使ってリクエスト内容、ヘッダなどを詳細に設定が可能。
ここで設定してる andExpect の内容は全て org.springframework.test.web.client.match.MockRestRequestMatchers のもの。

static import

example.java

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

GET

example.java
    @Test
    public void GetExample() {
        // 返却されるレスポンス
        String jsonResponseBody = "{\"id\": 99999,\"name\": \"exampleUser\"}";

        // 期待される結果
        User expectUser = new User() {{
            setId(99999);
            setName("exampleUser");
        }};

        // 呼び出す想定のURL
        String callEndpoint = "https://get-end-point-url";

        // create MockRestServiceServer
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer
            .expect(requestTo(callEndpoint))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(jsonResponseBody, MediaType.APPLICATION_JSON_UTF8));

        // 呼出し準備
        URI url = UriComponentsBuilder.fromHttpUrl(callEndpoint).build().toUri();
        HttpHeaders headers = new HttpHeaders();

        // restTemplateで実際に呼出し
        ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(null, headers), User.class);
        User responseUser = responseEntity.getBody();

        assertThat(responseUser.getId(), is(expectUser.getId()));
        assertThat(responseUser.getName(), is(expectUser.getName()));
    }

POST

example.java
    @Test
    public void PostExample() {
        // 返却されるレスポンス
        String jsonResponseBody = "{\"id\": 99999}";

        // 期待されるリクエストボディ
        String jsonRequestBody = "{\"name\":\"example man\",\"email\":\"example@example.com\",\"gender\":1}";

        // 期待される結果
        User expectUser = new User() {{
            setId(99999);
        }};

        // 呼び出すURL
        String callEndpoint = "https://post-end-point-url";

        // create MockRestServiceServer
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer
            .expect(requestTo(callEndpoint))
            .andExpect(method(HttpMethod.POST))
            // リクエストヘッダ内容の検証
            .andExpect(content().string(jsonRequestBody))
            .andRespond(withSuccess(jsonResponseBody, MediaType.APPLICATION_JSON_UTF8));

        // 呼出し準備
        URI url = UriComponentsBuilder.fromHttpUrl(callEndpoint).build().toUri();
        HttpHeaders headers = new HttpHeaders();

        // RequestBody
        ExamplePostRequest exampleRequest = new ExamplePostRequest() {{
            setName("example man");
            setEmail("example@example.com");
            setGender(MALE);
        }};
        ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity(exampleRequest, headers), User.class);
        User responseUser = responseEntity.getBody();
        assertThat(responseUser.getId(), is(expectUser.getId()));
    }

PUT

example.java

    @Test
    public void PutExample(){

        // 返却されるレスポンス
        String jsonResponseBody = "";

        // 期待されるリクエストボディ
        String jsonRequestBody = "{\"name\":\"example man\",\"email\":\"example@example.com\",\"gender\":1}";

        // 呼び出すURL
        String callEndpoint = "https://put-end-point-url";

        // ヘッダー
        HttpHeaders headers = new HttpHeaders();
        String exampleToken = String.format("Bearer %s", "EXAMPLE_BEARER_TOKEN");
        headers.add("Authorization", exampleToken);

        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer
            .expect(requestTo(callEndpoint))
            .andExpect(method(HttpMethod.POST))
            // リクエストヘッダ内容の検証
            .andExpect(header("Authorization", exampleToken))
            // リクエストボディ内容の検証
            .andExpect(content().string(jsonRequestBody))
            .andRespond(withSuccess(jsonResponseBody, MediaType.APPLICATION_JSON_UTF8));

        URI url = UriComponentsBuilder.fromHttpUrl(callEndpoint).build().toUri();

        // RequestBody
        ExamplePostRequest exampleRequest = new ExamplePostRequest() {{
            setName("example man");
            setEmail("example@example.com");
            setGender(MALE);
        }};
        // headers または exampleRequest をnullに返す等すると、正しく呼ばれていないため java.lang.AssertionError となる
        restTemplate.exchange(url, HttpMethod.POST, new HttpEntity(exampleRequest, headers), User.class);
    }
12
18
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
12
18