5
votes

I am trying to write test for my spring boot application. For the independent controller test, i have used @WebMvcTest but ran into some issues. Here is the basic structure of the code.

UserController has UserService class autowired.

LibraryController has LibraryService class autowired.

Here is the code for the UserControllerTest ::

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
   @Autowired
   private MockMvc mockMvc;
   
   @MockBean
    private UserService userServiceMock;

   @Test
   public void someTest(){}

}

It is giving the error while running the code in UserControllerTest:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'libraryController': Unsatisfied dependency expressed through field 'libraryService'; nested exception is org.springframework.beans.factory

As per my understanding, since we have specified UserController inside @WebMvcTest annotation, we need to mock only the dependency required by that controller. But it is asking for the libraryService which have no links with the usercontroller.

And yeah if we include the library service as MockBean inside the test, then it works fine. But if this is the case we have to mock each and every autowired beans as the program scales.

Any explanation is appreciated. Thanks in advance.

1
Your assumption is true. You only need to mock UserController class autowired fields. But it may be UserService uses LibraryController. Can you share UserService?barbakini
Sorry @barbakini but i cannot share the userService. These class actually doesnot exist, these are the assumed classes for explaining the issue i am facing. My code is huge and many services but i can make sure that userService has no dependency with the libraryService and libraryController.Mcoder
Ok i found the issue, but i quiet dont understand it. Any Explanation is appreciated. I had Service1 implementing interface Interface1, and service2 implementing interface2. So userService reqires service1 and i had used Interface1 as mockbean in the usercontrollertest, so when i replaced service1 as the mockbean rather than its interface it resolved the issue. Why cant we use interface as the mockbean? I had to specifically use the service to make it work...Mcoder

1 Answers

3
votes

Probably you've defined one of these annotations: @ComponentSacn, @EnableJpaRepositores and @EntityScan, on your main class.

By placing for instance @EnableJpaRepositores on the main class, you're indicating that JPA repositories must always be enabled, irrespective of which particular slice of functionality you're trying to test. The same applies to @ComponentScan and @EntityScan.