2016-04-14 12 views
1

私は、ユーザーが承認されているかどうかを確認するメソッドを持っています。ユーザーを認証するためにログインしてください。例外をスローするのではなく何かを返すメソッドを模擬する方法(PowerMock?)

私はこれを持っていますstaticOAuthUtil.retrieveAuthority()OAuthUtil.retrieveAuthority()文字列を返す、 "domain"としましょう。

私のコンストラクタは

public ImplService(){ 
    String authority = OAuthUtil.retrieveAuthority(); 
    //do something else 
} 

のようなものであると私は私が実際にテストしようとしているものです別の方法を持って、getList()を言います。

retrieveAuthority()は、Subjectがnullの場合は常にaWebApplicationExceptionをスローできますが、これは常にそうですが、これを完全に回避したいと考えています。だから、例外を投げるのではなく、私のモックが何かを返すようにしたい( "ドメイン")。それは可能ですか?

だから、私のテストは今、この権利のようなもので、例外が発生したときに、それは失敗します。

import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.powermock.api.mockito.PowerMockito; 
import org.powermock.modules.junit4.PowerMockRunner; 

@RunWith(PowerMockRunner.class) 
public class TestMine { 
    public ImplService impl; 

    @Before 
    public void setUp() { 
     PowerMockito.mockStatic(OAuthUtil.class); 
     PowerMockito.when(OAuthUtil.retrieveAuthority()).thenReturn("domain"); 
     ImplService impl = new ImplService(); 
    } 

    @Test 
    public void getListTest() throws NotFoundException { 
     Response response = impl.getList(); 
    } 
} 

答えて

2

はい、それは完全に可能です。追加する必要があります:

@PrepareForTest({OAuthUtil.class}) 
public class TestMine { //above this line 
関連する問題