java - jUnit:NPE 关于私有(private)成员初始化

标签 java junit initialization field jmockit

进行 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/

相关文章:

java - 如何锁定写入文件以便其他消费者无法使用

java - Junit-快速检查 : Generate String matching a pattern

c++ - 不稳定的行为

java - Spring 通过自定义身份验证提供程序记住我

java - 阅读 GSON 以获取顶级标签列表

java - org.hibernate.MappingException 在 Grails v3.2.9 中使用 tablePerConcreteClass 继承策略时

java - 莫基托 : How to ignore transitive dependencies

java - 如何用测试值和实际值填充大型 stub pojo?

c++ - 类成员初始化的最佳实践

ios - UI 不显示初始化程序的值