首页 > 解决方案 > 如何将 ActiveProfiles 与带有 WebMvcTest 的 Spring Boot 测试一起使用?

问题描述

我有一个单元测试正在使用@WebMvcTest. 控制器类自动装配我想模拟的服务类。我发现我可以使用@Profile@Configuration创建一个配置类来指定要在配置文件处于活动状态时使用的主 bean。我尝试向我的单元测试类添加一个活动配置文件,但它说它无法加载 ApplicationContext。我不确定在使用@WebMvcTest.

@ActiveProfiles("mockServices")
@RunWith(SpringRunner.class)
@WebMvcTest(VoteController.class)
public class VoteControllerTest {
...

看来我可能正在接近这个错误。任何帮助表示赞赏。

编辑:

这是我的配置类:

@Profile("mockService")
@Configuration
public class NotificationServiceTestConfiguration {

    @Bean
    @Primary
    public VotingService getVotingService() {
        return Mockito.mock(VotingService.class);
    }
}

我实际得到的错误是:

org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“VotingService”类型的合格 bean

我能够通过在我的单元测试类中使用@MockBeanfor VotingService 来解决它。但是,我想使用我在 NotificationServiceTestConfiguration 中的配置文件配置,而不必调用模拟 bean。

有什么想法吗?

标签: javaspringspring-bootspring-restcontrollerspring-test-mvc

解决方案


推荐阅读