Sangil's blog

https://github.com/ChoiSangIl Admin

Spring Boot RestTemplate 테스트(MockServer) DEV / WEB

2021-12-30 posted by sang12


Spring Boot에서 RestTemplate 호출(PUT)을 테스트하는 방법은 아래와 같다. 

RestTemplate객체를 MockServer의 인자값으로 넘겨 RestTemplate Mock서버를 만들어주고

호출하는 URL과 리턴받을 값을 설정 해준다. 그리고 RestTemplate로 호출해주면 된다.

PUT 메서드를 호출하려고 하니 template.put으로 호출하면 결과 값을 받아오지 못해서 exchange 함수를 사용하였다.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;

import java.net.URI;
import java.net.URISyntaxException;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;

@SpringBootTest
public class OrderServiceImplTest {

	@Autowired
	private RestTemplate template;

	private MockRestServiceServer mockServer;

	@BeforeEach
	public void init() throws URISyntaxException {
		mockServer = MockRestServiceServer.createServer(template);
		mockServer.expect(ExpectedCount.once(), 
		          requestTo(new URI("http://localhost:8083/product/stock/order")))
		          .andExpect(method(HttpMethod.PUT))
		          .andRespond(withStatus(HttpStatus.OK)
		          .contentType(MediaType.APPLICATION_JSON)
		          .body("minus stock..."));            
	}

	@Test
	public void testOrder() throws URISyntaxException {
	    HttpHeaders headers = new HttpHeaders();
	    headers.setContentType(MediaType.APPLICATION_JSON);
	    HttpEntity<String> entity = new HttpEntity<String>("", headers); 

	    ResponseEntity<String> response = template.exchange("http://localhost:8083/product/stock/order", HttpMethod.PUT, entity, String.class);
	    assertEquals("minus stock...", response.getBody());
	}
}

* 그리고 Autowried를 사용하여 RestTemplate 객체를 di 받아 왔는데 굳이 테스트를 위해 스프링을 올려가며 받아 와야 하나 싶다. 그래서 @Autowried 어노테이션을 제거하고 직접 RestTemplate객체를 생성하여 넣어주고 @SpringBootTest 어노테이션도 제거했다.

template = new RestTemplate();
mockServer = MockRestServiceServer.bindTo(template).build();

REPLY