【发布时间】: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 可以解决问题。
对此有何建议? 谢谢你:)
【问题讨论】: