gpt4 book ai didi

java - 在 Java EE 中测试 Singleton 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 17:29:00 24 4
gpt4 key购买 nike

我想使用 jUnit 测试 getCitation() 方法:

@Singleton
public class QuotesLoaderBean {

Properties quotes;
Properties names;

@PostConstruct
public void init() {
InputStream quotesInput = this.getClass().getClassLoader().getResourceAsStream("quotes.properties");
InputStream namesInput = this.getClass().getClassLoader().getResourceAsStream("names.properties");

quotes = new Properties();
names = new Properties();
try {
quotes.load(quotesInput);
names.load(namesInput);
} catch (IOException ex) {
Logger.getLogger(QuotesLoaderBean.class.getName()).log(Level.SEVERE, null, ex);
}
}

public Citation createCitation(String quote) {
Citation citation = new Citation();
citation.setQuote(quote);
citation.setWho(getName());
return citation;
}

public Citation getCitation() {
Citation citation = new Citation();
citation.setQuote(getQuote());
citation.setWho(getName());
return citation;
}

在测试文件中,我想注入(inject)单例并在测试方法中使用它。但后来我得到了 NullPointerException:

public class QuoteServiceTest {
@Inject
QuotesLoaderBean quotesLoaderBean;

public QuoteServiceTest() {
}

@BeforeClass
public static void setUpClass() {
}

@AfterClass
public static void tearDownClass() {
}

@Before
public void setUp() {
}

@After
public void tearDown() {
}

@Test
public void whenGetQuote_thenQuoteShouldBeReturned() {
quotesLoaderBean.getQuote();
}

}

测试方法还没有完成,我只是想展示当我从单例调用方法时发生的异常。在另一个服务类中,我可以轻松注入(inject)该类并调用方法。

最佳答案

注入(inject)由启用 DI 的容器在执行时处理。当您部署整个应用程序时,将设置一个容器并且注入(inject)工作正常。执行单元测试时,不会启动任何服务,并且任何 @Inject 最终都会将变量设置为 null,因为也不会启动任何容器。

因此,为了测试您的代码,您可能需要在 setUp 方法中构建服务:

public class QuotesServiceTest {

QuotesLoaderBean quotesLoaderBean;

// ...
@Before
public void setUp() {
quotesLoaderBean = new QuotesLoaderBean();
// call init method after construction
quotesLoaderBean.init();
}
// ...
}


关于java - 在 Java EE 中测试 Singleton 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61160751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com