我試圖用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到整數?
看起來像是Mockito問題。我從1.8.4更新到2.7.1,現在問題消失了。謝謝! – MarZ
@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),所以我不知道升級是什麼 - 但我很高興它的工作! –