package lesson6;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class _1_SpyingTest {
@Test
public void testSpy() {
List<String> realList = new ArrayList<>();
/**
* spy过的对象都会调用真正的方法
* 利用when-thenReturn来Mock不需要真正调用的方法
*/
List<String> list = spy(realList);
list.add("Mockito");
list.add("Fuck");
assertEquals(false, list.isEmpty());
assertEquals("Mockito", list.get(0));
assertEquals("Fuck", list.get(1));
when(list.isEmpty()).thenReturn(true);
assertEquals(true, list.isEmpty());
}
}
package lesson6;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class _2_SpyingAnnotationTest {
@Spy
List<String> list = new ArrayList<>();
@Test
public void testSpy() {
list.add("Mockito");
list.add("Fuck");
assertEquals(false, list.isEmpty());
assertEquals("Mockito", list.get(0));
assertEquals("Fuck", list.get(1));
when(list.isEmpty()).thenReturn(true);
assertEquals(true, list.isEmpty());
}
}