コントローラのユニットテスト
コントローラのテストをさぼっていたのでやってみた。
クッキーとか使っているからその辺りをどうやってテストするのかが今回の課題。
Cookie や SessionScope へのデータ設定
Cookie や SessionScope にあらかじめデータを設定した状態でテストしたい場合は tester.start() よりも先に設定しないといけないようだ。どちらも tester 経由で設定できるのでそれを使う。とても簡単だ。
- Cookie は tester.request.addCookie() で設定する
- SessionScope は tester.sessionScope() で設定する
public void クッキーが設定されている場合はリスト画面を表示する() throws Exception { // クッキーとセッションスコープを設定しておく int cookie_age_sec = 60*60*24*30; // 1 month Cookie cookie = new Cookie("user","delpiero"); cookie.setMaxAge(cookie_age_sec); cookie.setPath("/"); tester.request.addCookie(cookie); tester.sessionScope("user", "delpiero"); tester.start("/todo/indexList");
requestScope の設定を確認
コード内で requestScope() で値を設定していてそれをテストで確認したい場合も tester.requestScope() で簡単に取得できる。下の例は単純に "todo_high" というキーが設定されているかどうかを判定している。
// タスクを設定しているか assertThat(tester.requestScope("todo_high"),is(notNullValue()));
遷移先の判定
最終的にどの jspを表示したか判定したい場合は tester.getDestinationPath() で取得可能。
// 遷移先が正しいか assertThat(tester.getDestinationPath(), is("/todo/indexList.jsp"));
大体これらを駆使すればコントローラのテストは書けそうかな。
でもまだサービスの呼び出しを判定する方法などは不明。要調査。
Ajaxのレスポンスを判定する(2011/05/08 追記)
- Ajaxのレスポンス用のコントローラで、下記のように write() で文字列を渡すことで任意の文字列のレスポンスを返すことができる。
- この"hoge" が response に正しく設定されているかテストコードで判定したい場合。
@Override public Navigation run() throws Exception { response.getWriter().write("hoge"); response.getWriter().close(); return null; }
- テストコード
- tester.response.getOutputAsString() で write() された文字列を取得できる。
@Test public void testRun() throws Exception { tester.start("/xxxxxx"); assertThat(tester.response.getOutputAsString(), is("hoge")); }
getOutputAsString() で取得する文字列が想定外の空("")の場合、close() が漏れている可能性がある。これに気がつくまでにしばらくハマった‥。