How to test RestController



-BoardController.class

@RestController
public class BoardController {
@Autowired
private BoardService boardService;

public BoardController() {
System.
out.println("===> BoardController 생성");
}

@GetMapping("/hello")
public String hello(@RequestParam("name") String name) {
return "Hello : " + name;
}

}

Let's test BoardController code!


1. Using @WebMvcTest

- BoardControllerTest.class

import java.lang.String;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestParam;

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


@RunWith(SpringRunner.class)
@WebMvcTest
public class BoardControllerTest {
@Autowired
private MockMvc mockMvc;

@Test
public void testHello() throws Exception {
mockMvc.perform(get("/hello").param("name", "둘리"))
.andExpect(status().isOk())
.andExpect(content().string("Hello : 둘리"))
.andDo(print());
}
}

1) @WebMvcTest finds classes like Controller or RestController and create them on memory.

@WebMvcTest does not create classes like Service or Repository because they are not test cases.

2) "perform" method provides GET, POST, PUT, DELETE type method.

3) "param" method provides key-value parameter

4) "andExpect" method provides result verification.

5) "andDo" mthod provides action after completing test.


2. Using embeded Tomcat

We can test BoardController code starting with servlet container.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BoardControllerTest {
@Autowired
private TestRestTemplate restTemplate;

@Test
public void testHello() throws Exception {
String result = restTemplate.getForObject("/hello?name=둘리", String.class);
assertEquals("Hello : 둘리", result);
}
}

1) SpringBootTest.WebEnvironment.RANDOM_PORT means testing with servlet container.

2) First parameter of getForObject method is requestURL and second parameter is return value type.

3) Verify the result using assertEquals