Various method tests with MockRestServiceServer

What is MockRestServiceServer?

――There are many wonderful articles, so please check them out. - https://qiita.com/kazuki43zoo/items/fa9fea1c813f76080fe7 - https://qiita.com/yoshidasts/items/fd4e1f4434e3b6f40880

I will leave the code here as an example.

It is possible to set the URL, request contents, headers and methods that should be called by using MockRestServiceServer. If the call is not made correctly, you will get java.lang.AssertionError.

Created with MockRestServiceServer.createServer, you can use ʻandExpect to set the request contents, headers, etc. in detail. All the contents of ʻandExpect set here are those of ʻ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() {
        //Returned response
        String jsonResponseBody = "{\"id\": 99999,\"name\": \"exampleUser\"}";

        //Prospective result
        User expectUser = new User() {{
            setId(99999);
            setName("exampleUser");
        }};

        //Expected URL to call
        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));

        //Ready to call
        URI url = UriComponentsBuilder.fromHttpUrl(callEndpoint).build().toUri();
        HttpHeaders headers = new HttpHeaders();
        
        //Actually called with 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() {
        //Returned response
        String jsonResponseBody = "{\"id\": 99999}";

        //Expected request body
        String jsonRequestBody = "{\"name\":\"example man\",\"email\":\"[email protected]\",\"gender\":1}";

        //Prospective result
        User expectUser = new User() {{
            setId(99999);
        }};

        //URL to call
        String callEndpoint = "https://post-end-point-url";

        // create MockRestServiceServer
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer
            .expect(requestTo(callEndpoint))
            .andExpect(method(HttpMethod.POST))
            //Verification of request header contents
            .andExpect(content().string(jsonRequestBody))
            .andRespond(withSuccess(jsonResponseBody, MediaType.APPLICATION_JSON_UTF8));

        //Ready to call
        URI url = UriComponentsBuilder.fromHttpUrl(callEndpoint).build().toUri();
        HttpHeaders headers = new HttpHeaders();

        // RequestBody
        ExamplePostRequest exampleRequest = new ExamplePostRequest() {{
            setName("example man");
            setEmail("[email protected]");
            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(){

        //Returned response
        String jsonResponseBody = "";

        //Expected request body
        String jsonRequestBody = "{\"name\":\"example man\",\"email\":\"[email protected]\",\"gender\":1}";

        //URL to call
        String callEndpoint = "https://put-end-point-url";

        //header
        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))
            //Verification of request header contents
            .andExpect(header("Authorization", exampleToken))
            //Verification of request body contents
            .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("[email protected]");
            setGender(MALE);
        }};
        //If headers or exampleRequest is returned to null, it is not called correctly, so java.lang.AssertionError
        restTemplate.exchange(url, HttpMethod.POST, new HttpEntity(exampleRequest, headers), User.class);
    }

Recommended Posts

Various method tests with MockRestServiceServer
Various GraphQL tests
Write tests with Minitest
Integer check method with ruby
Conditional branch with helper method
[ruby] Method call with argument
Java unit tests with Mockito
Simulate the simplex method with GUI
[Ruby] Extracting elements with slice method
Introduction to algorithms with java-Shakutori method
Various confusing stories with Map # computeIfAbsent