【问题标题】:QuarkusTest with an ApplicationScoped bean and AfterEach-CallbackQuarkusTest 与 ApplicationScoped bean 和 AfterEach-Callback
【发布时间】:2021-01-21 13:43:23
【问题描述】:

我正在为标记为 ApplicationScoped 的 bean 编写一个简单的 QuarkusTest,非常简单:

package com.foo.bar;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class MyBean {

    String postConstructInitializedVariable;

    @PostConstruct
    public void postConstruct() {
        postConstructInitializedVariable = "foo";
    }

    public int getVariableLength() {
        return postConstructInitializedVariable.length();
    }
}

测试看起来像这样:

package com.foo.bar;

import javax.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
import static org.junit.jupiter.api.Assertions.assertEquals;

@QuarkusTest
class MyBeanTest {

    @Inject
    MyBean myBean;


    @AfterEach
    public void tearDown() {
        System.out.println(myBean.postConstructInitializedVariable.length());
    }


    @Test
    void test() {
        assertEquals(3, myBean.getVariableLength());
    }
}

测试失败并在 tearDown() 方法中出现 NPE - postConstructInitializedVariable 为空。 我找到了this in the docs,但后来我想知道如何在每次测试后正确执行代码以重置我的一些测试资源。 我感兴趣的是:用@Singleton 替换@ApplicationScoped 可以解决问题。

对此有何建议? 谢谢你:)

【问题讨论】:

    标签: java junit5 quarkus


    【解决方案1】:

    我认为 @ApplicationScoped bean 被 Quarkus 引导的方式以某种方式创建了 PostConstruct 注释方法的代理方法。如果您实际上在postConstruct() 方法中添加了logging/System.out 行,您将看到该方法仅在第一次调用bean 的公共方法之一时才调用一次。此后,postConstruct() 方法不再被调用,这是预期的工作方式

    【讨论】:

      猜你喜欢
      • 2012-12-23
      • 2012-12-02
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多