pooney
article thumbnail
Published 2020. 5. 15. 20:15
Spring boot Controller test Spring boot

일반적인 webmvc 테스트이면 mock를 사용해도 되지만 rest controller를 테스트 할 것이기 때문에 아래는 TestRestTemplate을 사용하여 test를 진행했다.

 

 

 

 

Controller 테스트

 

1. 테스트 할  controller인  HelloController 생성 

 

HelloController

package com.example.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
	
	@RequestMapping("/hi")
	public String hello() {
		
		return "Hi pooney 오신걸 환영합니다.";
	}

}

※ /hi를 요청시 "Hi pooney ~~ " 라는 String 값을 return 하게된다. 

 

 

 

2. test 유닛 생성 

 

Rest Controller를 테스트 할 것이기 때문에 TestRestTemplate를 사용하며 getForgetForEntity("요청url" , 리턴 타입)의 결과는  ResponseEntity<String>를 통하여 받아 응답코드와 리턴값을 받아 확인한다 

 

BootexApplicationTests

package com.example.demo;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
import org.junit.Ignore;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.demo.dto.User;
import com.example.demo.mapper.BootMapper;

@RunWith(SpringRunner.class)
//컨트롤러 테스트시 톰켓이랑 같이 뛰워야 하기 때문에 랜덤포트로 포트를 무시하고 스프리 부트로 테스트해라 라는 뜻 
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class BootexApplicationTests {
	
	//rest controller를 테스트 할 것이기 때문에 RestTemplate을 이용하는것이다. 
	@Autowired
	private TestRestTemplate restTemplate;
	
	
	@Test
	public void restTest() {
    	//getForgetForEntity("요청url" , 리턴 타입)
		ResponseEntity<String> re = restTemplate.getForEntity("/hi", String.class);
		System.out.println("re ====>"+ re);
		
	}
	

}

 

 

결과

응답코드 200Hi pooney가 정상적으로 출력되는 것을 확인 할 수 있다.

 

 

profile

pooney

@pooney

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!