본문 바로가기
Programming/Java, Spring

mockMvc로 rest json 데이터 테스트하기

by Renechoi 2023. 3. 8.

 

 

 

 

package org.zerock.domain;

import lombok.Data;

@Data
public class Ticket {

  private int tno;
  private String owner;
  private String grade;
}

 


@PostMapping("/ticket")
public Ticket convert(@RequestBody Ticket ticket) {

   log.info("convert.......ticket" + ticket);

   return ticket;

}

 

 

 

 

package org.zerock.controller;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.zerock.domain.Ticket;

import com.google.gson.Gson;

import lombok.Setter;
import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)

// Test for Controller
@WebAppConfiguration

@ContextConfiguration({ "file:src/main/webapp/WEB-INF/spring/root-context.xml",
    "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
// Java Config
// @ContextConfiguration(classes = {
// org.zerock.config.RootConfig.class,
// org.zerock.config.ServletConfig.class} )
@Log4j
public class SampleControllerTests {

  @Setter(onMethod_ = { @Autowired })
  private WebApplicationContext ctx;

  private MockMvc mockMvc;

  @Before
  public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
  }

  @Test
  public void testConvert() throws Exception {

    Ticket ticket = new Ticket();
    ticket.setTno(123);
    ticket.setOwner("Admin");
    ticket.setGrade("AAA");
    
    String jsonStr = new Gson().toJson(ticket);
    
    log.info(jsonStr);
    
    mockMvc.perform(post("/sample/ticket")
        .contentType(MediaType.APPLICATION_JSON)
        .content(jsonStr))
        .andExpect(status().is(200));
  }

}


 

반응형