1

How can I run only controller in @MicronautTest without running repositories/services only mocking them like in spring @WebMvcTest do?


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

        @Autowired
        private EmployeeService employeeService;

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

so I can test it in this way


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

example from https://www.baeldung.com/spring-boot-testing

saw303
  • 8,051
  • 7
  • 50
  • 90
Andrew Sasha
  • 1,254
  • 1
  • 11
  • 21

1 Answers1

0

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() >> []
   }
}
saw303
  • 8,051
  • 7
  • 50
  • 90