Search code examples
javaspringjunitmockito

Spring boot rest api unit test for controller


enter image description here

I have two controllers, one for users and one for roles. I have written test for the user controller, but when i try to run test it it gives me the following error:

"Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'uk.co.circuare.cube.service.user.repository.RoleRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}"

I am using mockito

public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper mapper;

    @MockBean
    private UserRepository repository; [![enter image description here][1]][1]

I have used two repositories in my usercontroller:

@Autowired private UserRepository repository;

@Autowired private RoleRepository roleRepository;


Solution

  • The solution to this is pretty straightforward — you need to provide every bean used in your controller class for the Application Context in your test class.

    You have mentioned an error saying that NoSuchBeanDefinitionException: No qualifying bean of type 'uk.co.circuare.cube.service.user.repository.RoleRepository' available: expected at least 1 bean which qualifies as autowire candidate.. It means that there is no bean of type RoleRepository in your test Application Context.

    You're using the @MockBean annotation. It will replace any existing bean of the same type in the application context. If no bean of the same type is defined, a new one will be added. I would recommend you to check the details on the mock annotation, which you're using in this article: Mockito.mock() vs @Mock vs @MockBean

    To resolve your issue, your test class should look like the following:

    public class UserControllerTest {
    
        @Autowired
        private MockMvc mockMvc;
    
        @Autowired
        private ObjectMapper mapper;
    
        @MockBean
        private UserRepository repository;
    
        @MockBean
        private RoleRepository roleRepository;
    
        ...
    }