Home > database >  Inject Instance of Service in WebMvcTest
Inject Instance of Service in WebMvcTest

Time:06-29

I have a test for MyController.java

@WebMvcTest(controllers = MyController.class)
class MyControllerTest {
  @Autowired 
  private MockMvc mockMvc;
  @MockBean 
  private SomeService service; //dependency of MyService
  @SpyBean 
  private MyService myService; //used in MyController
  @Test
  void testMyControllerCall() {
    //someTest
  }
}

If I annotate MyService with @SpyBean, it will call the real service and inject the bean in MyController, but my problem is that when I run coverage for MyControllerTest, it will not mark MyService as covered with tests, so I want a regular (Not mock or spy) implementation of MyService and inject it to MyController in the test class, but I don't know how.

If I put MyControllerTest outside test/java/controller package, it will mark MyService with coverage, but I don't want that fix as I want MyControllerTest to be in that package to be organized.

My folder structure is like this,

> main/java
> --/controller
> ----/MyController.java
> --/service
> ----/MyService.java 
> test/java
> --/controller
> ----/MyControllerTest.java

CodePudding user response:

A regular implementation of MyService and inject it to MyController can be achieved by @Autowired annotation as follows

@Autowired 
private MyService myService;

@MockBean should be used at the time of mocking the repositories or service. If you dont want to mock a service you can go ahead with @Autowired

CodePudding user response:

Based on your question description it looks like your coverage scan is ignoring test/java/controller package.

If it is so, can you please check if that is the case.

For calling Service, you can either use it with @Autowired or even create instance of your service using constructor, builder or whatever pattern available to you inside your test method.

Moreover, ideally you should have separate test class for service & test all operations there & in your controller test class you need to use mock/ spy of service so that controller can just mock service methods & test its operations.

  • Related