【问题标题】:How to exclude a Spring Boot Component from running in JUnit unit tests?如何排除 Spring Boot 组件在 JUnit 单元测试中运行?
【发布时间】:2021-09-17 15:13:44
【问题描述】:

如何在 JUnit 单元测试中排除 Spring Boot 组件的运行?

我的尝试

如果我错了,请纠正我。 @ComponantScan 是否在全局范围内排除一个类,包括主类和测试类?

由于我不想在全局范围内排除它,仅在单元测试期间,有什么办法可以做到吗?

@Component
public class DatabaseInitialization {

    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    private void postConstruct() {

        User user = new User();
        user.setEmail("app@test.com");
        user.setPassword("1234567");
        user.setFirstName("Charle");
        user.setLastName("P.");
        user.setIbanCode(2641874);
        user.setBicCode(63215472);
        user.setFriendsList("[]");

        userRepository.save(user);
    }
}

【问题讨论】:

  • 您能否发布更多关于您想要什么以及您尝试过什么的信息?
  • 感谢@WilliamAndrésBernal 的回复。现已更新。

标签: spring-boot junit


【解决方案1】:

@MockBean 注释将一个 bean 替换为另一个由 Mockito 模拟实现的 bean。您不会在模拟上存根任何方法。您只关心 bean 被替换为什么都不做的 bean。在您的测试类中:

@SpringBootTest
class MyTest {

    @MockBean
    private DatabaseInitialization databaseInitialization;

【讨论】:

  • 感谢@ChinHuang 的回答。如果我希望它排除它在main 中运行并在test 中使用它,这将解决问题,但这里是相反的。我想在main 中运行它,但不在test 中。
  • 我在运行测试时编辑了答案以替换 bean。
【解决方案2】:

我不了解您的确切用例,但此链接可能有助于了解如何在运行测试用例时排除自动配置类https://www.baeldung.com/spring-boot-exclude-auto-configuration-test

【讨论】:

    【解决方案3】:

    在测试期间阻止 @PostConstruct 运行:

    在您的测试文件夹中创建包含 post 构造的类并添加 @Primary 注释,使其优先于您的主项目中的类,如下所示。

    @Primary
    public class ClassContainingPostConstruct{   
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-29
      • 2021-01-24
      • 2017-12-25
      • 2017-02-20
      • 2018-05-11
      • 2018-06-01
      • 2018-02-20
      • 2021-09-05
      • 2018-03-21
      相关资源
      最近更新 更多