package com.yiautos.psf.order.service.impl;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.List;
public class MockitoTest {
@Test
public void testBehavior() {
//构建mock数据
List list = Mockito.mock(List.class);
list.add("1");
list.add("2");
System.out.println(list.get(0)); // 会得到null ,前面只是在记录行为而已,没有往list中添加数据
Mockito.verify(list).add("1"); // 正确,因为该行为被记住了
Mockito.verify(list).add("3");//报错,因为前面没有记录这个行为
}
@Test
public void testStub() {
List l = Mockito.mock(ArrayList.class);
Mockito.when(l.get(0)).thenReturn(10);
Mockito.when(l.get(1)).thenReturn(20);
Mockito.when(l.get(2)).thenThrow(new RuntimeException("no such element"));
Assert.assertEquals(10, (int) l.get(0));
Assert.assertEquals(20, (int) l.get(1));
Assert.assertNull(l.get(4));
l.get(2);
}
@Test
public void testSpy() {
List spyList = Mockito.spy(ArrayList.class);
spyList.add("one");
spyList.add("two");
Mockito.verify(spyList).add("one");
Mockito.verify(spyList).add("two");
Assert.assertEquals(2, spyList.size());
Mockito.doReturn(100).when(spyList).size();
Assert.assertEquals(100, spyList.size());
}
@Test
public void testVoidStub() {
List l = Mockito.mock(ArrayList.class);
Mockito.doReturn(10).when(l).get(1);
Mockito.doThrow(new RuntimeException("you cant clear this List")).when(l).clear();
Assert.assertEquals(10, (int) l.get(1));
l.clear();
}
@Test
public void testMatchers() {
List l = Mockito.mock(ArrayList.class);
Mockito.when(l.get(Mockito.anyInt())).thenReturn(100);
Assert.assertEquals(100, (int)l.get(999));
}
}