Skip to content

Instantly share code, notes, and snippets.

@mloza
Last active December 12, 2019 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloza/a2d420c3a2702226d200bffe6c9c9714 to your computer and use it in GitHub Desktop.
Save mloza/a2d420c3a2702226d200bffe6c9c9714 to your computer and use it in GitHub Desktop.
@Service
public class HelloService {
public String getHello() {
return "World";
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceTest {
@Autowired
private HelloService helloService;
@Test
public void shouldReturnCorrectText() {
assertThat(helloService.getHello()).isEqualTo("World");
}
}
@Controller
public class SimpleController {
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello!";
}
}
@Controller
public class SimpleController {
@Autowired
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello!";
}
@RequestMapping("/helloworld")
@ResponseBody
public String helloWorld() {
return "Hello " + helloService.getHello() + "!";
}
}
@RunWith(SpringRunner.class) #1
@WebMvcTest #2
public class SimpleControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnExpectedText() throws Exception {
mockMvc
.perform(get("/hello")) #3
.andExpect(status().isOk()) #4
.andExpect(content().string(containsString("Hello!"))); #5
}
}
@RunWith(SpringRunner.class)
@SpringBootTest #1
@AutoConfigureMockMvc #2
public class SimpleControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnExpectedText() throws Exception {
mockMvc
.perform(get("/hello"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello!")));
}
@Test
public void shouldReturnExpectedTextFromService() throws Exception {
mockMvc
.perform(get("/helloworld"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World!")));
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class SimpleControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private HelloService service; #1
@Test
public void shouldReturnExpectedText() throws Exception {
mockMvc
.perform(get("/hello"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello!")));
}
@Test
public void shouldReturnExpectedTextFromService() throws Exception {
when(service.getHello()).thenReturn("Mock"); #2
mockMvc
.perform(get("/helloworld"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello Mock!"))); #3
}
}
verify(service, times(1)).getHello();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment