2017-02-10 57 views
1

我堅持用mockito + junit編寫的測試用例 在這裏可以找到相同的幫助。該secenario如下嘲笑一個循環中的集合和邏輯

Class Application{ 
//property 1 
//property 2 
ForeignCollection<Key> keys; //Key class contains multiple keys for same application id and this field does not exist in application Table 
} 

這是我要創建我的測試用例

class ClassService{ 
    public Response method(Request request){ 
    //some lines of code 
    verifyKey(request,Application app); //a private method of same class 
    } 

    private void verifyKey(Request r,Application a){ 
     boolean matched = false; 
     Iterable<Key> keys = application.getSecretKeys().getWrappedIterable(); 
     for(Key key : keys) 
     if(request.headers("Key").equals(key.getKey())) secretKeyMatched=true; 
     if(!secretKeyMatched) throw new InvalidSecretKeyException(request.headers("Secret-Key"),"INVALID SECRET KEY"); 
    } 
    } 

的方法和下面是每當方法被調用測試用例

Class TestClass{ 
     @Mock 
     private ForeignCollection<Key> keyForeignCollection; 
     @Mock 
     Request request; 
     @Mock 
     Response response; 
     @Mock 
     ClassService classService; 
     //below are not mocked 
     private CloseableWrappedIterable<Key> closeableWrappedIterableOfKey; 
     private Iterable<Key> IterableOfKey; 
    @Before 
    public void setUp(){ 
     keyForeignCollection.add(Key object); 
     keyFoerignCollection.add(Key object); 
     } 
    public void shouldMethod(){ 
    keyForeignCollection.add(make(a(keyMaker.ApplicationSecretKey))); 
    application.setkeys(keyForeignCollection); 
    when(applicationSecretKeyForeignCollection.size()).thenReturn(2); 
    when(application.getKeys().getWrappedIterable()).thenReturn(closeableWrappedIterableOfKey); 
    when(request.headers("Key")).thenReturn("some-key"); when(application.getKeys().getWrappedIterable()).thenReturn(keyForeignCollection.getWrappedIterable()); 
// 
Response response = clasService.method(request); 
Map<String, String> responseBody = (Map<String, String>) response.getBody(); 

    } 
} 

從測試用例中,由於調用內部方法,即驗證(Request,Application),它會拋出空指針異常;

幫助!

+2

不要模擬集合:如果需要,請使用包含模擬值的實際集合。 –

+1

你的代碼輸入甚至不會編譯!你希望我們花**我們**的時間來幫助你解決**你的問題。所以**你**請花費5分鐘的時間A)正確地格式化/縮進你的所有代碼B)確保你真的發佈了你有的代碼。 – GhostCat

回答

1

假設你的目標是繞過對verifyKey方法的調用,而不是測試它;你可以use a Spy。使用@Spy註釋classService並模擬ClassService :: verifyKey(Request,Application)方法。

嘲笑一個void方法只寫

Mockito.doNothing().when(classService).verifyKey(x, y); 

Official doc about spies