进行 jUnit
测试,初始化我的 bean:
ShowProducts sp = new ShowProducts();
在 ShowProducts.java 中的以下行中出现 NullPointerException
:
private Locale locale = FacesContext.getCurrentInstance().getViewRoot()
.getLocale();
...
public Locale getLocale() {
return locale;
}
public String getLanguage() {
return locale.getLanguage();
}
public void localize() {
String localeParam = FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap().get("lang");
locale = new Locale(localeParam);
FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
}
如何在测试中正确初始化该字段?
编辑:
面孔配置:
<application>
<locale-config>
<default-locale>ru</default-locale>
<supported-locale>ua</supported-locale>
</locale-config>
<resource-bundle>
<base-name>msg</base-name>
<var>m</var>
</resource-bundle>
</application>
.xhtml:
<h:form>
<h:commandLink action="#{showProducts.localize}" includeViewParams="true"
rendered="#{showProducts.language=='ua'}">
#{m.rus}.
<f:param name="lang" value="ru"/>
</h:commandLink>
<h:commandLink action="#{showProducts.localize}" includeViewParams="true"
rendered="#{showProducts.language=='ru'}">
#{m.ukr}.
<f:param name="lang" value="ua"/>
</h:commandLink>
</h:form>
最佳答案
显然您的 JSF FacesContext 没有正确配置(我对面孔了解不多,但我认为在 jUnit 测试中设置和运行它们非常复杂)。然而,正在提供帮助——使用模拟。
在您的测试用例中,您希望确保: - ShowProducts 从面孔上下文/ View 根中检索正确的区域设置 - 正确地做其他事情。
我推荐你使用jmockit。你的测试用例会变成这样:
@Test
public void testShowProducts(@Cascading final FacesContext facesContext) {
final Locale locale = new Locale(...)
new Expectations() {
{
FacesContext.FacesContext.getCurrentInstance().getViewRoot().getLocale();
returns(locale);
}
};
ShowProducts sp = new ShowProducts();
... do your assertions other stuff there
}
这种技术适用于很多上下文,并大大简化了测试代码。
关于java - jUnit:NPE 关于私有(private)成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8343669/