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.
UserController
class autowired fields. But it may beUserService
usesLibraryController
. Can you shareUserService
? – barbakini