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 テストでの設定と実行はかなり複雑だと思います)。ただし、進行中のヘルプがあります - モッキングを使用してください。

あなたのテスト ケースでは、次のことを保証したいと考えています。

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 を持つ 2 番目のコンストラクターを追加し、それを単体テストに使用することです。次に、デフォルトのコンストラクターが 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 に答える