4

Struts 2 と Tomcat をサーブレット コンテナーとして使用するアプリケーションで、cucumber-jvm を使用して受け入れテスト (動作のテスト) を作成しています。コードのある時点で、HttpSessionによって作成された Struts 2 からユーザーをフェッチする必要がありHttpServletRequestます。

私はテストを行っており、Tomcat を実行していないため、アクティブなセッションがなく、NullPointerException.

呼び出す必要があるコードは次のとおりです。

public final static getActiveUser() {
    return (User) getSession().getAttribute("ACTIVE_USER");
}

そして getSession メソッド:

public final static HttpSession getSession() {
    final HttpServletRequest request (HttpServletRequest)ActionContext.
                          getContext().get(StrutsStatics.HTTP_REQUEST);
    return request.getSession();
}

正直なところ、私は Struts 2 についてあまり知らないので、少し助けが必要です。Tomcatの例が埋め込まれたこのcucumber-jvmを見てきましたが、理解するのに苦労しています。

このStruts 2 Junit Tutorialも見てきました。悲しいことに、これはすべての機能を十分にカバーしているわけではなくStrutsTestCase、最も単純な使用例です (すべてを考慮すると、かなり役に立たないチュートリアルです)。

では、ユーザーがアプリケーションを使用しているかのように受け入れテストを実行するにはどうすればよいでしょうか?


アップデート:

答えてくれたスティーブン・ベニテスに感謝します!

私は2つのことをしなければなりませんでした:

  1. 提案されているように、HttpServletRequest をモックします。
  2. HttpSession をモックして、必要な属性を取得します。

cucumber-jvm テストに追加したコードは次のとおりです。

public class StepDefs {
    User user;
    HttpServletRequest request;
    HttpSession session;

    @Before
    public void prepareTests() {
        // create a user

        // mock the session using mockito
        session = Mockito.mock(HttpSession.class);
        Mockito.when(session.getAttribute("ACTIVE_USER").thenReturn(user);

        // mock the HttpServletRequest
        request = Mockito.mock(HttpServletRequest);
        Mockito.when(request.getSession()).thenReturn(session);

        // set the context
        Map<String, Object> contextMap = new HashMap<String, Object>();
        contextMap.put(StrutsStatics.HTTP_REQUEST, request);
        ActionContext.setContext(new ActionContext(contextMap));
    }

    @After
    public void destroyTests() {
        user = null;
        request = null;
        session = null;
        ActionContext.setContext(null);
    }

}

4

1 に答える 1

2

AnActionContextは、アクションが実行されるコンテキストを表すリクエストごとのオブジェクトです。静的メソッドgetContext()setContext(ActionContext context)は、ThreadLocal. この場合、テストの前にこれを呼び出すことができます。

Map<String, Object> contextMap = new HashMap<String, Object>();
contextMap.put(StrutsStatics.HTTP_REQUEST, yourMockHttpServletRequest);
ActionContext.setContext(new ActionContext(contextMap));

そして、次のようにしてクリーンアップします。

ActionContext.setContext(null);

この例では、テストしているメソッドが必要とするもののみを提供します。ここで提供しなかったコードに基づいてマップに追加のエントリが必要な場合は、それに応じて追加してください。

それが役立つことを願っています。

于 2013-07-18T15:27:00.827 に答える