Here is an example how you can do it. The example uses Spock but the same concept also works with JUnit 5.
@MicronautTest
public class EmployeeRestControllerIntegrationSpec extends Specification {
@Inject
EmployeeRestController controller
@MockBean(EmployeeService) { // if EmployeeService is an interface put the impl class name here such as EmployeeServiceImpl.
return Mock(EmployeeService) // here leave the interface since you want to create a mock of the interface
}
@Inject // Inject the EmployeeService mock here to control the behaviour in the test.
EmployeeService employeeService
void “Test something“() {
when:
List<Employee> employees = controller.getAllEmployees()
then:
employees.isEmpty()
and: “return an empty list“
employeeService.findAllEmployees() >> []
}
}
This example calls the controller directly. But if you create a declarative Micronaut http client you can inject the http client and make an HTTP request to the controller.
@Client(“/api“)
public interface EmployeeRestClient {
@Get(“/employees“)
List<Employee> findAllEmployees();
}
Now lets rewrite the test.
@MicronautTest
public class EmployeeRestControllerIntegrationSpec extends Specification {
@Inject
EmployeeRestClient employeeRestClient
@MockBean(EmployeeService) { // if EmployeeService is an interface put the impl class name here such as EmployeeServiceImpl.
return Mock(EmployeeService)
}
@Inject // Inject the EmployeeService mock here to control the behaviour in the test.
EmployeeService employeeService
void “Test something“() {
when:
List<Employee> employees = employeeRestClient.findAllEmployees()
then:
employees.isEmpty()
and: “return an empty list“
employeeService.findAllEmployees() >> []
}
}