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つのことをしなければなりませんでした:
- 提案されているように、HttpServletRequest をモックします。
- 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);
}
}