programing

mockMvc로 응답체에서 JSON을 확인하는 방법

skycolor 2023. 8. 20. 10:34
반응형

mockMvc로 응답체에서 JSON을 확인하는 방법

이것은 내 컨트롤러 안에 있는 나의 방법으로 주석을 달았습니다.@Controller

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject getServerAlertFilters(@PathVariable String serverName) {
        JSONObject json = new JSONObject();
        List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(filteredAlerts);
        json.put(SelfServiceConstants.DATA, jsonArray);
        return json;
    }

임신했어요.{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}내 아들로서.

그리고 이건 제 JUNIT 테스트입니다.

@Test
    public final void testAlertFilterView() {       
        try {           
            MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
                    .accept("application/json"))
                    .andDo(print()).andReturn();
            String content = result.getResponse().getContentAsString();
            LOG.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

다음은 콘솔 출력입니다.

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

심지어.result.getResponse().getContentAsString()빈 문자열입니다.

테스트 케이스를 완료할 수 있도록 JUnit 테스트 방법에서 JSON을 받을 수 있는 방법을 누가 제안해 줄 수 있습니까?

유닛 테스트는 TestNG를 사용합니다.하지만 스프링 테스트 프레임워크에서는 둘 다 비슷하게 보입니다.그래서 저는 당신의 시험이 아래와 같다고 생각합니다.

@Test
public void testAlertFilterView() throws Exception {
    this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").
            .andExpect(status().isOk())
            .andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}"));
    }

json 키와 값을 확인하려면 jsonpath를 사용할 수 있습니다..andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

당신은 그것을 발견할지도 모릅니다.content().json()해결할 수 없습니다. 추가하십시오.

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

406 Not Acceptable상태 코드는 스프링이 객체를 json으로 변환할 수 없음을 의미합니다.컨트롤러 메소드에서 String을 반환하고 다음을 수행할 수 있습니다.return json.toString();직접 구성할 수도 있습니다.HandlerMethodReturnValueHandlerSpringMVC에서 @ResponseBody를 사용하여 JsonObject를 반환하는 이 유사한 질문을 확인하십시오.

아래 forget 및 post 메서드를 사용해 보십시오.

@Autowired
private MuffinRepository muffinRepository;

@Test
public void testGetMethod throws Exception(){
    Muffin muffin = new Muffin("Butterscotch");
    muffin.setId(1L);
    
    BddMockito.given(muffinRepository.findOne(1L)).
        willReturn(muffin);
        
    mockMvc.perform(MockMvcRequestBuilders.
        get("/muffins/1")).
        andExpect(MockMvcResutMatchers.status().isOk()).
        andExpect(MockMvcResutMatchers.content().string("{\"id\":1, "flavor":"Butterscotch"}"));    
}

//Test to do post operation
@Test
public void testPostMethod throws Exception(){
    Muffin muffin = new Muffin("Butterscotch");
    muffin.setId(1L);
    
    BddMockito.given(muffinRepository.findOne(1L)).
        willReturn(muffin);
        
    mockMvc.perform(MockMvcRequestBuilders.
        post("/muffins")
        .content(convertObjectToJsonString(muffin))
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResutMatchers.status().isCreated())
        .andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(muffin))); 
}

응답이 비어 있는 경우 오버라이드해야 합니다.equals()그리고.hashCode()의 방법.Entity저장소에서 다음 작업을 수행합니다.

//Converts Object to Json String
private String convertObjectToJsonString(Muffin muffin) throws JsonProcessingException{
    ObjectWriter writer = new ObjectWriter().writer().withDefaultPrettyPrinter();
    return writer.writeValueAsString(muffin);
}

JSON의 특정 필드에서 몇 가지 값을 확인하려는 경우

.andExpect(MockMvcResultMatchers.jsonPath("$.message",
    AllOf.allOf(
        StringContains.containsString("name: must not be null"),
        StringContains.containsString("type: must not be null")
    )));

테스트 수업에서 어떻게 보이는지.JUNIT4.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.core.AllOf;
import org.hamcrest.core.StringContains;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(MockitoJUnitRunner.class)
public class YourControllerTest {

  @Mock
  private YourService service;

  private MockMvc mvc;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders
        .standaloneSetup(new YourController(service))
        .setControllerAdvice(new YourExceptionHandler())
        .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
        .build();
  }

  @Test
  public void yourControllerMethodName_400_validation() throws Exception {
    String path = "/orders/{orderId}/items";
    Integer orderId = 123;

    YourRequestDto requestDto = YourTestFactory.buildYourRequestDto();
    requestDto.setName(null);
    requestDto.setType(null);

    YourResponseDto expected = YourTestFactory.buildYourResponseDto(requestDto);

    Mockito
        .when(service.someMethod(orderId, requestDto))
        .thenReturn(expected);

    mvc
        .perform(
            MockMvcRequestBuilders.post(path, orderId)
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(requestDto))
        )
        .andExpect(MockMvcResultMatchers.status().isBadRequest())
        .andExpect(MockMvcResultMatchers.jsonPath("$.message",
            AllOf.allOf(
                StringContains.containsString("name: must not be null"),
                StringContains.containsString("type: must not be null")
            )));
  }
}

JSON 응답을 확인하는 방법은 두 가지가 있습니다.두 가지 모두에 대해 안내해 드리겠습니다(위 질문에서 테스트 방법을 선택하고 응답을 가정함).{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}상기와 같이)

방법 1) 완전한 JSON 주장

@Test
public final void testAlertFilterView() {       
    mockMvc.perform(get("/getServerAlertFilters/v2v2v2/")
           .contentType("application/json"))
           .andExpect(status().isOk())
           // you may even read bigger json responses from file and convert it to string, instead of simply hardcoding it in test class
           .andExpect(content().json("{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}"))     
}

방법 2) 응답의 특정 키 값 주장(중복 코드를 작성하지 않음)

.andExpect(jsonPath("$.data[0].useRegEx").value(false))
.andExpect(jsonPath("$.data[0].hosts").value("v2v2v2"));

또 다른 필요한 것은 수입 명세서입니다.

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

언급URL : https://stackoverflow.com/questions/30482934/how-to-check-json-in-response-body-with-mockmvc

반응형