简体   繁体   中英

Spring boot rest api unit test for cotroller

在此处输入图像描述

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;

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;

    ...
}

You also have to mock RoleRepository in your test class.

@ExtendWith(MockitoExtension.class)
public class UserControllerTest {

    @InjectMocks
    private UserController userController;

    @Mock
    private ObjectMapper mapper;

    @Mock
    private UserRepository repository;

    @Mock
    private RoleRepository roleRepository;

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM