@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
void hello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello keesun"))
.andDo(print());
}
}
RANDOM_PORT, DEFINED_PORT
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleControllerTest {
@Autowired
TestRestTemplate testRestTemplate;
@Test
void hello() throws Exception {
String result = testRestTemplate.getForObject("/", String.class);
assertThat(result).isEqualTo("hello keesun");
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleControllerTest {
@Autowired
TestRestTemplate testRestTemplate;
@MockBean
SampleService sampleService;
@Test
void hello() throws Exception {
when(sampleService.getName()).thenReturn("whiteship");
String result = testRestTemplate.getForObject("/hello", String.class);
assertThat(result).isEqualTo("hello whiteship");
}
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleControllerTest {
@Autowired
WebTestClient webTestClient;
@MockBean
SampleService sampleService;
@Test
void hello() throws Exception {
when(sampleService.getName()).thenReturn("whiteship");
webTestClient.get().uri("/hello").exchange().expectStatus().isOk()
.expectBody(String.class).isEqualTo("hello whiteship");
}
}
@JsonTest
class SampleControllerTest {
@Autowired
JacksonTester<SampleDomain> jacksonTester;
}
@WebMvcTest(SampleController.class)
class SampleControllerTest {
@MockBean
SampleService sampleService;
@Autowired
MockMvc mockMvc;
@Test
void hello() throws Exception {
when(sampleService.getName()).thenReturn("whiteship");
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello whiteship"))
.andDo(print());
}
}
@RestController
public class SampleController {
Logger logger = LoggerFactory.getLogger(SampleController.class);
...
@GetMapping("/hello")
public String hello() {
logger.info("holoman");
return "hello " + sampleService.getName();
}
}
@WebMvcTest
@ExtendWith(OutputCaptureExtension.class)
class SampleControllerTest {
@MockBean
SampleService sampleService;
@Autowired
MockMvc mockMvc;
@Test
void hello(CapturedOutput capturedOutput) throws Exception {
when(sampleService.getName()).thenReturn("whiteship");
mockMvc.perform(get("/hello")).andExpect(content().string("hello whiteship"));
assertThat(capturedOutput.toString()).contains("holoman");
}
}
ConfigFileApplicationContextInitializer