0

jUnit进行测试,初始化我的bean :

ShowProducts sp = new ShowProducts();

在ShowProducts.javaNullPointerException中进入以下行:

    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>
4

2 回答 2

3

显然您的 JSF FacesContext 配置不正确(我对面孔了解不多,但我认为在 jUnit 测试中设置和运行它们非常复杂)。但是,有一些帮助正在进行中 - 使用模拟。

在您的测试用例中,您希望确保: - ShowProducts 从面部上下文/视图根中检索正确的语言环境 - 正确执行其他操作。

我建议你使用 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
 }

该技术适用于很多上下文,大大简化了测试代码。

于 2011-12-01T15:39:18.837 回答
1

访问静态方法使编写测试变得困难。

使用构造函数传递 Locale 或使用 setter。

最简单的更改是添加第二个以 Locale 作为参数的构造函数并将其用于单元测试。然后默认构造函数初始化 FacesContext 中的字段。

为了实现更简洁的设计,您应该提取Localizer处理所有本地化的位置,以便将ShowProducts不需要的与需要的FacesContext分开Localizer

定位器将类似于:

public class Localizer {
    public void localize() {
        String localeParam = FacesContext.getCurrentInstance()
                .getExternalContext().getRequestParameterMap().get("lang");
        locale = new Locale(localeParam);
        FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
    }
}

这与ShowProducts. 不确定你需要什么getLanguge()

于 2011-12-01T15:34:20.837 回答