当前位置: 首页 > 工具软件 > jQuery Spy > 使用案例 >

6. spy

伍玮
2023-12-01
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());
    }
}
 类似资料: