这是一个示例,您可以如何做到这一点。该示例使用 Spock,但同样的概念也适用于 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() >> []
}
}
此示例直接调用控制器。但是,如果您创建声明性 Micronaut http 客户端,您可以注入 http 客户端并向控制器发出 HTTP 请求。
@Client(“/api“)
public interface EmployeeRestClient {
@Get(“/employees“)
List<Employee> findAllEmployees();
}
现在让我们重写测试。
@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() >> []
}
}