Java org.mockito.Spy 代码实例

・14 分钟阅读

以下是展示如何使用org.mockito.Spy的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test
public void should_prevent_spying_on_interfaces() throws Exception {
    class WithSpy {
        @Spy List<String> list;
    }
    WithSpy withSpy = new WithSpy();
    try {
        MockitoAnnotations.initMocks(withSpy);
        fail();
    } catch (MockitoException e) {
        Assertions.assertThat(e.getMessage()).contains("is an interface and it cannot be spied on");
    }
}
 

实例 2


@Test
public void should_allow_spying_on_interfaces_when_instance_is_concrete() throws Exception {
    class WithSpy {
        @Spy List<String> list = new LinkedList<String>();
    }
    WithSpy withSpy = new WithSpy();
    //when
    MockitoAnnotations.initMocks(withSpy);
    //then
    verify(withSpy.list, never()).clear();
}
 

实例 3


@Test
public void should_report_when_no_arg_less_constructor() throws Exception {
    class FailingSpy {
        @Spy
        NoValidConstructor noValidConstructor;
    }
    try {
        MockitoAnnotations.initMocks(new FailingSpy());
        fail();
    } catch (MockitoException e) {
        Assertions.assertThat(e.getMessage()).contains("0-arg constructor");
    }
}
 

实例 4


@Test
public void should_report_when_constructor_is_explosive() throws Exception {
    class FailingSpy {
        @Spy
        ThrowingConstructor throwingConstructor;
    }
    try {
        MockitoAnnotations.initMocks(new FailingSpy());
        fail();
    } catch (MockitoException e) {
        Assertions.assertThat(e.getMessage()).contains("Unable to create mock instance");
    }
}
 

实例 5


@Test
public void should_spy_abstract_class() throws Exception {
    class SpyAbstractClass {
        @Spy AbstractList<String> list;
        List<String> asSingletonList(String s) {
            when(list.size()).thenReturn(1);
            when(list.get(0)).thenReturn(s);
            return list;
        }
    }
    SpyAbstractClass withSpy = new SpyAbstractClass();
    MockitoAnnotations.initMocks(withSpy);
    assertEquals(Arrays.asList("a"), withSpy.asSingletonList("a"));
}
 

实例 6


@Test
public void should_spy_inner_class() throws Exception {
 class WithMockAndSpy {
        @Spy private InnerStrength strength;
        @Mock private List<String> list;
        abstract class InnerStrength {
            private final String name;
            InnerStrength() {
                // Make sure that @Mock fields are always injected before @Spy fields.
                assertNotNull(list);
                // Make sure constructor is indeed called.
                this.name = "inner";
            }
            abstract String strength();
            String fullStrength() {
                return name + " " + strength();
            }
        }
    }
    WithMockAndSpy outer = new WithMockAndSpy();
    MockitoAnnotations.initMocks(outer);
    when(outer.strength.strength()).thenReturn("strength");
    assertEquals("inner strength", outer.strength.fullStrength());
}
 

实例 7


@Test
public void should_report_when_encosing_instance_is_needed() throws Exception {
    class Outer {
        class Inner {}
    }
    class WithSpy {
        @Spy private Outer.Inner inner;
    }
    try {
        MockitoAnnotations.initMocks(new WithSpy());
        fail();
    } catch (MockitoException e) {
        assertContains("@Spy annotation can only initialize inner classes", e.getMessage());
    }
}
 

实例 8


@Override
protected boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {
    FieldReader fieldReader = new FieldReader(fieldOwner, field);
    // TODO refoctor : code duplicated in SpyAnnotationEngine
    if(!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) {
        try {
            Object instance = fieldReader.read();
            if (new MockUtil().isMock(instance)) {
                // A. instance has been spied earlier
                // B. protect against multiple use of MockitoAnnotations.initMocks()
                Mockito.reset(instance);
            } else {
                new FieldSetter(fieldOwner, field).set(
                    Mockito.mock(instance.getClass(), withSettings()
                        .spiedInstance(instance)
                        .defaultAnswer(Mockito.CALLS_REAL_METHODS)
                        .name(field.getName()))
                );
            }
        } catch (Exception e) {
            throw new MockitoException("Problems initiating spied field " + field.getName(), e);
        }
    }
    return false;
}
 

实例 9


@SuppressWarnings({"deprecation", "unchecked"})
private Collection<Object> instanceMocksOf(Object instance) {
    return Fields.allDeclaredFieldsOf(instance)
                                        .filter(annotatedBy(Mock.class,
                                                            Spy.class,
                                                            MockitoAnnotations.Mock.class))
                                        .notNull()
                                        .assignedValues();
}
 

实例 10


private Set<Object> instanceMocksIn(Object instance, Class<?> clazz) {
    Set<Object> instanceMocks = new HashSet<Object>();
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        if (declaredField.isAnnotationPresent(Mock.class) || declaredField.isAnnotationPresent(Spy.class)) {
            declaredField.setAccessible(true);
            try {
                Object fieldValue = declaredField.get(instance);
                if (fieldValue != null) {
                    instanceMocks.add(fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new MockitoException("Could not access field " + declaredField.getName());
            }
        }
    }
    return instanceMocks;
}
 

实例 11


@SuppressWarnings({"deprecation", "unchecked"})
private Collection<Object> instanceMocksOf(Object instance) {
    return Fields.allDeclaredFieldsOf(instance)
                                        .filter(annotatedBy(Mock.class,
                                                            Spy.class,
                                                            MockitoAnnotations.Mock.class))
                                        .notNull()
                                        .assignedValues();
}
 

实例 12


private Set<Object> instanceMocksIn(Object instance, Class<?> clazz) {
    Set<Object> instanceMocks = new HashSet<Object>();
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        if (declaredField.isAnnotationPresent(Mock.class) || declaredField.isAnnotationPresent(Spy.class)) {
            declaredField.setAccessible(true);
            try {
                Object fieldValue = declaredField.get(instance);
                if (fieldValue != null) {
                    instanceMocks.add(fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new MockitoException("Could not access field " + declaredField.getName());
            }
        }
    }
    return instanceMocks;
}
 

实例 13


@SuppressWarnings("deprecation")
@Override
public void process(Class<?> context, Object testClass) {
        Field[] fields = context.getDeclaredFields();
        for (Field field : fields) {
                if (field.isAnnotationPresent(Spy.class)) {
                        try {
                                Whitebox.invokeMethod(this, Spy.class, field, new Class<?>[] { Mock.class,
                                                org.mockito.MockitoAnnotations.Mock.class, Captor.class });
                        } catch (RuntimeException e) {
                                throw e;
                        } catch (Exception e1) {
                                throw new RuntimeException(e1);
                        }
                        boolean wasAccessible = field.isAccessible();
                        field.setAccessible(true);
                        try {
                                Object instance = field.get(testClass);
                                if (instance == null) {
                                        throw new MockitoException("Cannot create a @Spy for '" + field.getName()
                                                        + "' field because the *instance* is missingn" + "Example of correct usage of @Spy:n"
                                                        + "   @Spy List mock = new LinkedList();n");
                                }
                                field.set(testClass, PowerMockito.spy(instance));
                        } catch (IllegalAccessException e) {
                                throw new MockitoException("Problems initiating spied field " + field.getName(), e);
                        } finally {
                                field.setAccessible(wasAccessible);
                        }
                }
        }
}
 

实例 14


@Override
@SuppressWarnings("deprecation")
// for MockitoAnnotations.Mock
public void process(Class<?> context, Object testInstance) {
   Field[] fields = context.getDeclaredFields();
   for (Field field : fields) {
      if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) {
         assertNoIncompatibleAnnotations(Spy.class, field, com.googlecode.gwt.test.Mock.class,
                  Mock.class, org.mockito.MockitoAnnotations.Mock.class, Captor.class);
         Object instance = null;
         try {
            FieldInitializationReport report = new FieldInitializer(testInstance, field).initialize();
            instance = report.fieldInstance();
         } catch (MockitoException e) {
            new Reporter().cannotInitializeForSpyAnnotation(field.getName(), e);
         }
         try {
            if (new MockUtil().isMock(instance)) {
               // instance has been spied earlier
               // for example happens when MockitoAnnotations.initMocks is called two times.
               Mockito.reset(instance);
            } else {
               field.setAccessible(true);
               field.set(testInstance, Mockito.mock(
                        instance.getClass(),
                        withSettings().spiedInstance(instance).defaultAnswer(
                                 Mockito.CALLS_REAL_METHODS).name(field.getName())));
            }
         } catch (IllegalAccessException e) {
            throw new MockitoException("Problems initiating spied field " + field.getName(), e);
         }
      }
   }
}
 

实例 15


@Test
public void shouldGetAnnotatedFieldsGivenPackageField() {
        // Given
        Class<ClassWithAnnnotations> clazz = ClassWithAnnnotations.class;
        Class<? extends Annotation> annotationClass = Spy.class;
        // When
        Set<Field> fields = retriever.getAnnotatedFields(clazz, annotationClass);
        // Then
        assertEquals(1, fields.size());
        assertTrue(fields.contains(getField(clazz, "defaultAnnotatedField")));
}
 
讨论
淘淘あ西西 profile image