2017-02-02 38 views
0

我試圖用Mockito來捕獲類型爲「int」的參數。如何爲原始類型創建Mockito ArgumentCaptor?

這是我的測試代碼:

public class Client { 

    private final Board board; 
    private final Server server; 

    private void makeMove() { 
    nextMove = 11; 
    server.nextMove(nextMove); 
    } 

    public void moveAccepted(boolean accepted) { 
    if (accepted) { 
     board.updateBoard(nextMove); 
    } else { 
     ... 
    } 
    } 
} 

這是測試代碼:

@RunWith(MockitoJUnitRunner.class) 
public class ClientTest { 

    private Client client; 

    @Mock 
    private Board mockBoard; 

    @Mock 
    private Server mockServer; 

    @Captor 
    private ArgumentCaptor<Integer> moveCaptor; 

    @Test 
    public void testGamePlay() { 
    client.forceNextMove(); 
    verify(mockServer).nextMove(moveCaptor.capture()); // NPE here 
    client.moveAccepted(true); 
    verify(mockBoard).updateBoard(eq(moveCaptor.getValue())); 
    } 
} 

結果我得到NullPointerException異常測試,試圖在捕獲值傳遞給server.nextMove調用。

我已經檢查過,那個captor不是null。 如果我更改server.nextMove的參數類型從int整數然後一切正常。

我也沒有找到任何方法來創建類似「IntArgumentCaptor」(例如anyInt爲匹配者)。

有沒有什麼辦法可以使測試工作,沒有server.nextMove到整數

回答

2

您正在使用哪個版本的Mockito?根據ArgumentCaptor's implementation,你不需要做任何不同的事情。例如,由於ArgumentCaptor必須通過forClass(通過它可以確定要返回哪種原語類型)或@Captor(它可以讀取字段類型並適當地調用forClass)創建,因此這比調用any()更明智。

public T capture() { 
    Mockito.argThat(capturingMatcher); 
    return defaultValue(clazz); 
} 

Primitives.defaultValue

/** 
* Returns the boxed default value for a primitive or a primitive wrapper. 
* 
* @param primitiveOrWrapperType The type to lookup the default value 
* @return The boxed default values as defined in Java Language Specification, 
*   <code>null</code> if the type is neither a primitive nor a wrapper 
*/ 
public static <T> T defaultValue(Class<T> primitiveOrWrapperType) { 
    return (T) PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.get(primitiveOrWrapperType); 
} 

如果NPE是由你控制的代碼來了,那麼這是一個重要的標誌:它表示的Mockito呼叫期間推遲到您的實現verify,這可能表明Server.nextMove是unmockable。如果Server是最終的,Server.nextMove是最終的,或者上述任何一個是受保護的或包私有的(因爲某些版本的Mockito在Java編譯器創建這些工作時會產生麻煩)。

如果你可以看到ArgumentCaptor.capture()返回null(不同於上面的代碼),那麼這聽起來像是一個Mockito錯誤。

+0

看起來像是Mockito問題。我從1.8.4更新到2.7.1,現在問題消失了。謝謝! – MarZ

+0

@MarZ很高興聽到!有趣的是,ArgumentCaptor [似乎在1.8.4中有類型適當的「HandyReturnValues」邏輯](http://grepcode.com/file/repo1.maven.org/maven2/org.mockito/mockito-core/1.8.4 /org/mockito/ArgumentCaptor.java?av=f),所以我不知道升級是什麼 - 但我很高興它的工作! –