網頁

2021/6/28

Spring Boot Test MockMvc 取得回應JSON結果 get response json

Spring Boot Test 印出Controller REST API回應的json內容。


範例環境:

  • Java 8
  • Spring Boot 2.3.2.RELEASE
  • JUnit 5
  • Lombok

API回應json資料中代表的物件EmployeeDto

EmployeeDto

package com.abc.demo.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeDto {

    private long id;
    private String name;
    private Integer age;
}

回應內容包裝在回應代碼及訊息的物件Response

Response

package com.abc.demo.controller.response;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Response<T> {

    private String code;
    private String message;

    private T data;

    public static <T> Response<T> success(T data) {
        Response<T> response = new Response<>();
        response.setCode("0");
        response.setMessage("success");
        response.setData(data);
        return response;
    }
}

DemoController提供API /employees回傳員工資料。

DemoController

package com.abc.demo.controller;

import com.abc.demo.controller.response.Response;
import com.abc.demo.dto.EmployeeDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
public class DemoController {

    @GetMapping(value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<EmployeeDto>> getEmployees() {
        log.info("取得員工列表");
        List<EmployeeDto> employeeDtoList = Arrays.asList(
                new EmployeeDto(1, "John", 33),
                new EmployeeDto(2, "Mary", 28)
        );
        return Response.success(employeeDtoList);
    }
}

測試

DemoControllerTests中以MockMvc.perform()呼叫API /employees並呼叫.andReturn()取得回應MvcResult,然後呼叫MvcResult.getResponse().getContentAsString()取得回應的json字串並印出。

DemoControllerTests

package com.abc.demo.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@AutoConfigureMockMvc
@SpringBootTest
public class DemoControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void employees() throws Exception {
        MvcResult result = mockMvc.perform(get("/employees"))
                .andExpect(status().isOk())
                .andReturn();

        System.out.println(result.getResponse().getContentAsString()); // {"code":"0","message":"success","data":[{"id":1,"name":"John","age":33},{"id":2,"name":"Mary","age":28}]}
    }
}


沒有留言:

張貼留言