1. 验证结果
package mockito;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class WhenReturn {
@Test
public void whenReturn() {
//模拟创建一个List对象
List listMock = mock(List.class);
when(listMock.size()).thenReturn(10);
when(listMock.add("")).thenReturn(false);
when(listMock.remove(anyString())).thenReturn(true);
when(listMock.get(0)).thenReturn("mock value");
//验证结果
assertEquals(10, listMock.size());
assertTrue(listMock.remove("not save value"));
assertFalse(listMock.add("false value"));
assertEquals("mock value", listMock.get(0));
}
@Test(expected = RuntimeException.class)
public void consecutiveCalls() {
List mockList = mock(List.class);
//模拟连续调用返回期望值,如果分开,则只有最后一个有效
when(mockList.get(0)).thenReturn(0);
when(mockList.get(0)).thenReturn(1);
when(mockList.get(0)).thenReturn(2);
when(mockList.get(1)).thenReturn(0).thenReturn(1).thenThrow(new RuntimeException());
assertEquals(2, mockList.get(0));
assertEquals(2, mockList.get(0));
assertEquals(0, mockList.get(1));
assertEquals(1, mockList.get(1));
//第三次或更多调用都会抛出异常
mockList.get(1);
}
@Test
public void callMethodAndAnswer() {
//模拟创建一个Person对象
Person person = mock(Person.class);
when(person.isPerson(1)).thenCallRealMethod();
//使用回调生成期望值
when(person.getPerson(anyInt(), anyString())).thenAnswer(invocation -> {
Object[] arguments = invocation.getArguments();
if ("1".equals(arguments[0].toString()))
return "1 answer";
return "other answer";
});
doCallRealMethod().when(person).print(2, "name");
person.print(2, "name");
assertTrue(person.isPerson(1));
assertEquals("1 answer", person.getPerson(1, "name"));
assertEquals("other answer", person.getPerson(2, "name"));
//mock对象使用Answer来对未预设的调用返回默认期望值
List mock = mock(List.class, new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return 999;
}
});
//下面的get(1)没有预设,通常情况下会返回NULL,但是使用了Answer改变了默认期望值
assertEquals(999, mock.get(1));
//下面的size()没有预设,通常情况下会返回0,但是使用了Answer改变了默认期望值
assertEquals(999, mock.size());
}
public class Person {
private String name;
private int id;
public String getPerson(int id, String name) {
return id + ": " + name;
}
public boolean isPerson(int id) {
return 1 == id;
}
public void print(int id, String name) {
System.out.println(id + ": " + name);
}
}
}