2017-02-10 53 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