Quarkus 忽略测试依赖

Quarkus ignore dependencies for test

在我的 quarkus 应用程序中,我在单独的 gradle project/module 中实现了存储库实现,部分原因是我希望能够确保单元测试不使用数据库等

麻烦的是,如果我想在测试中使用任何注入的依赖项,我需要使用@QuarkusTest,然后构建或启动确保满足所有个依赖项。

有没有什么方法可以解决这个问题而不涉及模拟每个外部依赖项,例如?

我也在使用 weld-junit to run unit tests on CDI components. In the past I have been using cdiunit,这很棒,但它不支持 JUnit 5。两者的想法都是在真正的 CDI 容器中以最小配置启动测试。重要的部分是您明确控制哪些 bean 可用于注入,因此系统会跳过 bean 发现部分。这使得测试相当快:CDI 开销只有几秒钟。这两个系统都允许您为您想要的任何依赖项提供模拟实例 - 我一直在使用 Mockito 来管理模拟。

最小的 Maven 设置(参见 here 是使用启用 JUnit 5 的 Maven surefire 插件版本,例如:

<pluginManagement>
    <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.2</version>
    <plugin>
</pluginManagement>

以及其他依赖项:

        <dependency>
            <groupId>org.jboss.weld</groupId>
            <artifactId>weld-junit5</artifactId>
            <version>${version.weld-junit5}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${version.junit.jupiter}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${version.junit.jupiter}</version>
            <scope>test</scope>
        </dependency>
        <!-- If you want Mockito: -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>${version.mockito}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <version>${version.mockito}</version>
            <scope>test</scope>
        </dependency>

有了这些,您就可以编写 & 运行 测试 (an example) for your CDI beans (example):

// weld-junit5 annotation - there are other ways to activate weld-junit5
// in your tests, and more features for controlling the container,
// read the full docs!
@EnableAutoWeld
// add real bean implementations in the DI container
@AddBeanClasses(RealBeanDependency.class)
// add extensions if you need
@AddExtensions({Extension1.class, Extension2.class})
// activate scopes, if you need
@ActivateScopes(RequestScoped.class)
// add automatic creation of mocks with Mockito (@Mock)
@ExtendWith(MockitoExtension.class)
public class MyClassTest {
    // an example of introducing mocks to the DI container
    @Produces @Mock
    private ArticleService articleService;

    // injected the "System Under Test"
    // weld-junit will automatically add it to the available beans
    @Inject
    private MyClass sut;

    @Test
    void test() {
        // this runs inside the minimal CDI container
        // read the docs about details, e.g. it starts
        // a fresh container for each test (I think)
    }
}