Skip to content

Instantly share code, notes, and snippets.

@mloza

mloza/HelloService.java

Last active Dec 12, 2019
Embed
What would you like to do?
@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
You can’t perform that action at this time.