System.out.println()
을 통해 눈으로 확인 하지 않아도 된다package com.pgrrr.book.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication
SpringApplication.run
package com.pgrrr.book.springboot.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // 1
public class HelloController {
@GetMapping("/hello") // 2
public String hello() {
return "hello";
}
}
@RestController
@ResponseBody
를 각 메소드마다 선언 했던 것을 한번에 사용@GetMapping
@RequestMapping(method = RequestMethod.GET)
대신 사용package com.pgrrr.book.springboot.web;
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 static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class) // 1
@WebMvcTest(controllers = HelloController.class) // 2
public class HelloControllerTest {
@Autowired // 3
private MockMvc mvc; // 4
@WithMockUser(roles = "USER")
@Test
public void hello가_리턴된다() throws Exception {
String hello = "hello";
mvc.perform(get("/hello")) // 5
.andExpect(status().isOk()) // 6
.andExpect(content().string(hello)); // 7
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
@Controller
, @ControllerAdvice
사용 가능@Service
, @Component,
@Repository
사용 불가능@Autowired
private MockMvc mvc
mvc.perform(get(”/hello”))
.andExpect(status().isOk())
mvc.perform
의 결과를 검증.andExpect(content().string(hello))
mvc.perform
의 결과를 검증@WithMockUser(roles = “USER”)
@WithMockUser
@WithAnonymousUser
@WithUserDetails
브라우저로 한 번씩 검증은 하되 테스트 코드는 꼭 작성
테스트 코드를 먼저 검증 후 필요하면 브라우저로 확인