Controller and Service
@Service
class MyService {
fun getMessage(): String {
return "hello!"
}
}
Calling the service from a controller,
@RestController
class MyController(private val myService: MyService) {
@GetMapping("/")
fun sayHello(): String {
return myService.getMessage()
}
}
Testing with @WebMvcTest
@WebMvcTest
class UnitTest(@Autowired val mockMvc: MockMvc) {
@MockBean
private lateinit var myService: MyService
@Test
fun shouldReturnHello() {
`when`(myService.getMessage()).thenReturn("hello!")
this.mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andDo(print())
.andExpect(status().isOk)
.andExpect(content().string("hello!"))
}
}
Testing with @SpringBootTest
@SpringBootTest
@AutoConfigureMockMvc
class UnitTest(@Autowired val mockMvc: MockMvc) {
@MockBean
private lateinit var myService: MyService
@Test
fun shouldReturnHello() {
`when`(myService.getMessage()).thenReturn("hello!")
this.mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andDo(print())
.andExpect(status().isOk)
.andExpect(content().string("hello!"))
}
}