Home > front end >  Spring boot rest api unit test for cotroller
Spring boot rest api unit test for cotroller

Time:09-03

enter image description here

I have two controller user and role for crud, i have write test for user controller, but when i try to run test it give 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 repository in my usercontroller

@Autowired private UserRepository repository;

@Autowired private RoleRepository roleRepository;

CodePudding user response:

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;

    ...
}

CodePudding user response:

You also have to mock RoleRepository in your test class.

CodePudding user response:

@ExtendWith(MockitoExtension.class)
public class UserControllerTest {

    @InjectMocks
    private UserController userController;

    @Mock
    private ObjectMapper mapper;

    @Mock
    private UserRepository repository;

    @Mock
    private RoleRepository roleRepository;

    ...
}
  • Related