1

我怎样才能在@MicronautTest 中只运行控制器而不运行存储库/服务,只像在春天@WebMvcTest那样模拟它们?


    @RestController
    @RequestMapping("/api")
    public class EmployeeRestController {

        @Autowired
        private EmployeeService employeeService;

        @GetMapping("/employees")
        public List<Employee> getAllEmployees() {
            return employeeService.getAllEmployees();
        }
    }

所以我可以用这种方式测试它


    @RunWith(SpringRunner.class)
    @WebMvcTest(EmployeeRestController.class)
    public class EmployeeRestControllerIntegrationTest {
    
        @Autowired
        private MockMvc mvc;
    
        @MockBean
        private EmployeeService service;
    
        // write test cases here
    }

来自https://www.baeldung.com/spring-boot-testing的示例

4

1 回答 1

0

这是一个示例,您可以如何做到这一点。该示例使用 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() >> []
   }
}
于 2022-01-13T05:37:12.687 回答