如果要提取,运行或断言由方法返回或调用的参数。
这将从第一个和第二个参数中提取参数并返回Ticket对象。
when(mockTicketMaker.getTicket(any(Double.class),any(String.class)))
.thenAnswer(new Answer<String>(){
private int ticketNum=1;
@Override public Ticket answer(InvocationOnMock invocation) throws Throwable {
Double price=(Double)invocation.getArguments()[0];
String destination = (String) invocation.getArguments()[1];
assertEquals(new Double(123.56), price);
return new Ticket();
}
}
);
答案 0 :(得分:0)
看起来你想对传递给方法的参数断言。 Mockito以the ArgumentCaptor<> class的形式提供了更优雅的解决方案,而不是在答案中使用内联答案和断言。
鉴于
public class TicketMaker {
public void getTicket(Double arg1, String arg2) {
}
}
您可以在测试中编写以下内容
@Test
public void captureArguments() {
TicketMaker mockTicketMaker = Mockito.mock(TicketMaker.class);
mockTicketMaker.getTicket(23.0d, "something");
ArgumentCaptor<Double> doubleCaptor = ArgumentCaptor.forClass(Double.class);
ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
Mockito.verify(mockTicketMaker).getTicket(doubleCaptor.capture(), stringCaptor.capture());
assertThat(doubleCaptor.getValue()).isEqualTo(23.0d);
assertThat(stringCaptor.getValue()).isEqualTo("something");
}