SpringSecurtiyのSecurityContextを利用したクラスのテスト方法
投稿者: hikaruworld : 2011 1月 26
SpringSecurityを利用するとControllerからもこんな感じで、簡単に主体情報を取得できます。
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ただし、この実装を利用した場合、
ユニットテスト時は当然主体情報を取得できません。
認証情報がありませんので。。。
そのためテストをする場合は、
その認証情報を以下のように、
TestingAuthenticationTokenとしてSecurityContextHolderに格納してあげると良いとのこと。
// User情報は通常格納する主体情報を利用します。
// SpringSecurityを利用する場合は大体UserDetailsを継承しているかと。
User user = new User() {};
// Test用の認証Tokenに格納します。
// 第1引数に実際のユーザ情報、第2引数に資格情報を設定します。
// 後者は@Securedのテストをするような場合に必要になりますが、詳しくは次回。
Authentication authentication = new TestingAuthenticationToken(principal , null);
// SecurityContextの実装クラスをインスタンス化します。
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(authentication);
// staticメソッドでSecurityContextに設定します。
SecurityContextHolder.setContext(context );
実際にテストで利用する場合は@Before辺りで読むと楽です。
参考:Tapestry 5 with Spring Security – problem with unit tests.
以上です。