2016-04-21 11 views
3

私はSpringアプリケーションを持っており、ControllerをテストするためにJUnitテストをビルドしています。Springセキュリティに依存するJUnitでSpringコントローラをテストする

問題がControllerの内側に、私はこのコードを呼び出すことです。つまり

final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
final String userName = authentication.getName(); 

を、私はこのControllerを呼び出す前に認証する必要があります。

private MockMvc mockMvc; 

    @Test 
    public void getPageTest() throws Exception{ 
     final ProcessFileController controller = new ProcessFileController(); 
     mockMvc = standaloneSetup(controller).build(); 

    mockMvc.perform(get(URI.create("/processFile.html")).sessionAttr("freeTrialEmailAddress", "")).andExpect(view().name("processFile")); 
     } 

そして私は、私がログインしていないので、私のauthenticationnullあるので、それは私にfinal String userName = authentication.getName();NullPointerException権利を与えて実行します。私はこのコードでJUnitテストを書きました。

質問:認証を模擬する方法はありますか?すべてのアイデアは大歓迎です。

ありがとうございます。

+1

は、なぜあなたは手動でそれを行う代わりにAuthenticationPrincipal' @ '使用していますか? – chrylis

+0

chrylis、アーキテクチャは '@ AuthenticationPrincipal'を使うようには設計されていませんでしたが、私は現在のアーキテクチャでこれを処理する方法が必要です。あなたの答えをありがとう。 –

答えて

3

@AuthenticationPrincipalを使用するのが理想ですが、それがオプションでない場合は、SecurityContextAuthenticationインスタンスを設定し、テストで使用できるようにする必要があります。

これを行うには、ヘルパークラスの静的メソッドを使用できます。その後、テストであなたは、単に

SecurityHelper.setupSecurityContext("user", "password", "g1", "g2");

5

春のセキュリティバージョン4を呼び出すことができます

public static void setupSecurityContext(String username, String password, String... groups) 
{ 
    List<GrantedAuthority> authorities = new ArrayList<>(); 
    for (String group : groups) 
    { 
    authorities.add(new SimpleGrantedAuthority(group)); 
    } 

    UserDetails user = new UserDetails(username, password, authorities); 
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, password); 
    SecurityContextHolder.getContext().setAuthentication(token); 
} 

は、このに関するいくつかのきちんとした改善点を紹介しました。

まず、あなたはそれが見えるのMavenで、テストのためのクラスパス内のテストフレームワークを持っていることを確認するように:

<dependency> 
    <groupId>org.springframework.security</groupId> 
    <artifactId>spring-security-test</artifactId> 
    <version>4.0.4.RELEASE</version> 
    <scope>test</scope> 
</dependency> 

便利な輸入:

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; 
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; 

テストのセットアップ:

mockMvc = webAppContextSetup(applicationContext).apply(springSecurity()).build(); 

(私は、あなたが単一のコントローラではなくWebApplicationContextを必要としていると思う)

その後のようなテストなもの:

mockMvc.perform(get(...).with(user("username").roles("USER"))).andExpect(...); 
関連する問題