Java 使用ApplicationScoped bean和每次回调后进行QuarkusTest测试
我正在为标记为Java 使用ApplicationScoped bean和每次回调后进行QuarkusTest测试,java,junit5,quarkus,Java,Junit5,Quarkus,我正在为标记为ApplicationScoped且非常简单的bean编写一个简单的QuarkusTest: package com.foo.bar; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class MyBean { String postConstructInitializedVariab
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-PostConstructinizalizedVariable为null。
我找到了,但是我想知道如何在每次测试之后正确地执行代码来重置一些测试资源。
我感兴趣的是:用@Singleton替换@applications解决了这个问题
有什么建议吗?
谢谢:)我认为Quarkus引导
@ApplicationScoped
bean的方式以某种方式创建了构造后注释方法的代理方法。如果您实际上在postConstruct()
方法中添加了logging/System.out行,您将看到只有在第一次调用bean的一个公共方法时才会调用该方法一次。此后,不会再次调用postConstruct()
方法,这就是预期的工作方式