0

The scenario is as follows.

I have a controller that I want to test which has a dependency on a single service injected through the constructor. The injected service its self is dependent on another service injected through its constructor. At runtime, autowired injection creates the services and injects them as intended.

The problem is that when testing the controller in a unit test I cant just mock the service that the controller is directly dependent on, for some reason autowire attempts to create the entire chain unless I provide mocks for all the dependencies.

I would expect that if my test had a @MockBean for all direct dependencies of the controller that would be sufficient but that does not appear to be the case. The test has to provide mocks for every dependency in the graph.

This isn't much of a problem with this simple case but it becomes very problematic when there are dozens of services and components in the dependency graph.

How can I get autowire and the WebMvcTest to stop at the top level of the graph when all the direct dependencies are mocked?

Eli Pulsifer
  • 713
  • 9
  • 25
  • which version of spring boot are you using ? I remember having such a problem back in the time but it was solved at some point – Guillaume Pansier Mar 04 '20 at 19:01
  • Ok I found the issue I was talking about: https://github.com/spring-projects/spring-boot/issues/6663, which is about field injection, so I don't think it applies in your case – Guillaume Pansier Mar 04 '20 at 19:04
  • Do you have any additional configuration on the application class? (The one with @SpringBootApplication.) This often happens because of ComponentScan without proper filter. https://stackoverflow.com/questions/60260228/have-my-spring-test-slice-scan-a-single-class-instead-of-the-whole-package/60260986#60260986 – Josef Cech Mar 05 '20 at 07:25
  • I have component scan set up to scan the api service and references submodules: @ComponentScan("com.a.b.customerservice.app") @ComponentScan("com.a.b.customerservice.dao.services") @ComponentScan("com.a.b.customerservice.auth.services") public class Application { – Eli Pulsifer Mar 05 '20 at 16:09

0 Answers0