2016-12-30 3 views
0

私は現在ログインしているユーザーに関する詳細を取得しているconrtollerクラスを持っています。メソッド名は 'LoggedInUser()'です。このメソッドは一般的には完全に実行されていますが、特定のメソッドの単体テストケースを生成することはできません。AutowiredオブジェクトをモックしながらMockito.when()が正しく動作しない

私はMockitoを使用していますが、 'Mockito.when()'が正しく動作していません。 私はすべての関連する質問を行ったが、解決することはできませんでした。

以下は私がこれまで行ってきたことです。

Controller.java私はそれが再びインスタンス化された「校長」として動作しない場合がありますことを、別の記事で読んでいるのでコメント内の行が書き込まれ

@Service 
    @Transactional 
    Public class Controller implements someInterface { 

private LoggedInUser getUser(HttpServletRequest request) { 
      principal = request.getUserPrincipal(); 
      Authentication tk = (Authentication) principal; 
      //Authentication tk = (Authentication)(request.getUserPrincipal()); 
      LoggedInUser user = (LoggedInUser) tk.getPrincipal(); 
      return user; 
     } 

。だから私はそれをバイパスしようとしましたが、うまくいきませんでした。

Test.java

@Mock 
    private HttpServletRequest httpServletRequest; 

public void tes() { 
     //httpServletRequest = Mockito.mock(HttpServletRequest.class); 
     Principal principal= Mockito.mock(Principal.class); 
     Mockito.when(httpServletRequest.getUserPrincipal()).thenReturn(principal); 
....... 
....... 
} 

デバッグ中に、それはコントローラクラスにAutowiredだと私はrequest (object of HttpServletRequest)の値を取得していますが、principalは常にnullです。 ご協力いただければ幸いです!

+0

コメントを解除 'TES(内側の1本のライン)あなたはモックする必要がある参照が割り当てられていない場合、' – ppasler

+0

あなたのモックが影響していませんモックの価値とテストされたメソッドのコードを表示する必要があります。 – davidxxx

+0

[mcve]を提供してください。 – Tom

答えて

0

Autowiredだから私はをモックできませんでした。それゆえ、request.getUserPrincipal()は、メソッドを呼び出さないので、常にNullのままです。 次のようにコードを置き換えました。

Controller.java

@Service 
    @Transactional 
    Public class Controller implements someInterface { 

    public LoggedInUser getUser() { 
     LoggedInUser user = (LoggedInUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
     return user; 
    } 

Test.java

@Mock 
    private Principal principal; 

    @Mock 
    private SecurityContext securitycontext; 

    @Mock 
    private Authentication authentication; 
    public void test() { 
     LoggedInUser user = new LoggedInUser(); 
     Mockito.when(authentication.getPrincipal()).thenReturn(user); 
     Mockito.when(securitycontext.getAuthentication()).thenReturn(authentication); 
     SecurityContextHolder.setContext(securitycontext); 
....... 
....... 
} 
0

擬似オブジェクトを注入していませんhttpServletRequest。テストのために、この嘲笑されたオブジェクトをgetUserメソッドに渡す必要があります。

+0

と私はそれをどのように正確に行うことができますか? –

+0

あなたのメソッドがプライベートでない場合は、 'httpServletRequest = Mockito.mock(HttpServletRequest.class);'を参考にして 'getUser(httpServletRequest)'を呼び出すことができます。あなたのサーブレットに渡される場所を確認する必要があります –

+0

デバッグ中、 'request(object of HttpServletRequest)'の値はコントローラクラスのAutowiredになっていますが、 'principal'は常にnullです。 –

2

このテストクラスに@RunWith(MockitoJUnitRunner.class)を追加しましたか?ので、@Mockが動作します。私はあなたが嘲笑してをgetUser()に渡していると仮定しています。

+0

番号。私は 'MockitoAnnotations.initMocks(this)'を追加しました。 –

+0

はい、あなたのモックを初期化します。 – zodi91

+0

完全な例を提供できますか? – zodi91