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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With