Java 类org.mockito.internal.util.reflection.FieldSetter 实例源码

项目:astor    文件:MockitoAnnotations.java   
@SuppressWarnings("deprecation")
static void processAnnotationDeprecatedWay(AnnotationEngine annotationEngine, Object testClass, Field field) {
    boolean alreadyAssigned = false;
    for(Annotation annotation : field.getAnnotations()) {
        Object mock = annotationEngine.createMockFor(annotation, field);
        if (mock != null) {
            throwIfAlreadyAssigned(field, alreadyAssigned);
            alreadyAssigned = true;                
            try {
                new FieldSetter(testClass, field).set(mock);
            } catch (Exception e) {
                throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
                        + annotation, e);
            }
        }
    }
}
项目:astor    文件:FinalMockCandidateFilter.java   
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
    if(mocks.size() == 1) {
        final Object matchingMock = mocks.iterator().next();

        return new OngoingInjecter() {
            public boolean thenInject() {
                try {
                    if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
                        new FieldSetter(fieldInstance, field).set(matchingMock);
                    }
                } catch (Exception e) {
                    throw new MockitoException("Problems injecting dependency in " + field.getName(), e);
                }
                return true;
            }
        };
    }

    return new OngoingInjecter() {
        public boolean thenInject() {
            return false;
        }
    };

}
项目:astor    文件:DefaultAnnotationEngine.java   
public void process(Class<?> clazz, Object testClass) {
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        boolean alreadyAssigned = false;
        for(Annotation annotation : field.getAnnotations()) {           
            Object mock = createMockFor(annotation, field);
            if (mock != null) {
                throwIfAlreadyAssigned(field, alreadyAssigned);                    
                alreadyAssigned = true;                    
                try {
                    new FieldSetter(testClass, field).set(mock);
                } catch (Exception e) {
                    throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
                            + annotation, e);
                }
            }        
        }
    }
}
项目:astor    文件:MockitoAnnotations.java   
@SuppressWarnings("deprecation")
static void processAnnotationDeprecatedWay(AnnotationEngine annotationEngine, Object testClass, Field field) {
    boolean alreadyAssigned = false;
    for(Annotation annotation : field.getAnnotations()) {
        Object mock = annotationEngine.createMockFor(annotation, field);
        if (mock != null) {
            throwIfAlreadyAssigned(field, alreadyAssigned);
            alreadyAssigned = true;                
            try {
                new FieldSetter(testClass, field).set(mock);
            } catch (Exception e) {
                throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
                        + annotation, e);
            }
        }
    }
}
项目:astor    文件:FinalMockCandidateFilter.java   
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
    if(mocks.size() == 1) {
        final Object matchingMock = mocks.iterator().next();

        return new OngoingInjecter() {
            public Object thenInject() {
                try {
                    if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
                        new FieldSetter(fieldInstance, field).set(matchingMock);
                    }
                } catch (RuntimeException e) {
                    new Reporter().cannotInjectDependency(field, matchingMock, e);
                }
                return matchingMock;
            }
        };
    }

    return new OngoingInjecter() {
        public Object thenInject() {
            return null;
        }
    };

}
项目:astor    文件:DefaultAnnotationEngine.java   
public void process(Class<?> clazz, Object testInstance) {
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        boolean alreadyAssigned = false;
        for(Annotation annotation : field.getAnnotations()) {           
            Object mock = createMockFor(annotation, field);
            if (mock != null) {
                throwIfAlreadyAssigned(field, alreadyAssigned);                    
                alreadyAssigned = true;                    
                try {
                    new FieldSetter(testInstance, field).set(mock);
                } catch (Exception e) {
                    throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
                            + annotation, e);
                }
            }        
        }
    }
}
项目:xpath-to-xml    文件:AbstractStepExprTest.java   
@Test
public void shouldReturnNodesResolvedByStepExprOnly() throws NoSuchFieldException {
    // given
    setUpResolvableExpr();
    Field stepExprPredicatesField = stepExpr.getClass().getSuperclass().getDeclaredField("predicates");
    FieldSetter.setField(stepExpr, stepExprPredicatesField, Collections.emptyList());

    // when
    IterableNodeView<TestNode> result = stepExpr.resolve(new ViewContext<>(navigator, parentNode, false));

    // then
    assertThat((Iterable<?>) result).isNotEmpty();
    verify(predicate1, never()).test(any(ViewContext.class));
    verify(predicate2, never()).test(any(ViewContext.class));
}
项目:ServiceCOLDCache    文件:DebugHttpFilterTest.java   
private void writeField(Object obj, String field, Object v) {
    try {
        Field executorField = obj.getClass().getDeclaredField(field);
        FieldSetter fieldSetter = new FieldSetter(obj, executorField);
        fieldSetter.set(v);
    } catch (NoSuchFieldException e) {
        Assert.fail(e.getMessage());
    }
}
项目:ServiceCOLDCache    文件:DebugManagerTest.java   
private void writeField(Object obj, String field, Object v) {
    try {
        Field executorField = obj.getClass().getDeclaredField(field);
        FieldSetter fieldSetter = new FieldSetter(obj, executorField);
        fieldSetter.set(v);
    } catch (NoSuchFieldException e) {
        Assert.fail(e.getMessage());
    }
}
项目:ServiceCOLDCache    文件:CacheStatsTest.java   
private void writeField(Object obj, String field, Object v) {
    try {
        Field executorField = obj.getClass().getDeclaredField(field);
        FieldSetter fieldSetter = new FieldSetter(obj, executorField);
        fieldSetter.set(v);
    } catch (NoSuchFieldException e) {
        Assert.fail(e.getMessage());
    }
}
项目:AndroidUnitTest    文件:AnnotationContextManager.java   
@Override
public void execute(@NonNull Object target, @NonNull Context context) {
    if (contextField != null) {
        Context appContext = context;
        appContext = Mockito.spy(appContext);
        new FieldSetter(target, this.contextField).set(appContext);
    }
}
项目:AndroidUnitTest    文件:AnnotationViewManager.java   
private void initView(@NonNull Object target, @NonNull Context context, @NonNull Field viewField) {
    Class viewClass = viewField.getType();
    View view = null;
    try {
        view = (View) viewClass.getDeclaredConstructor(Context.class).newInstance(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
    view = Mockito.spy(view);
    new FieldSetter(target, viewField).set(view);
}
项目:AndroidUnitTest    文件:AnnotationFragmentManager.java   
public void initFragment(@NonNull Object target, @NonNull Field fragmentField) {
    RFragment fragmentAnnotation = fragmentField.getAnnotation(RFragment.class);

    Class fragmentClass = fragmentField.getType();
    Fragment fragment = null;
    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Impossible to instantiate a fragment using the default constructor");
    }

    fragment = Mockito.spy(fragment);
    new FieldSetter(target, fragmentField).set(fragment);

    //if no activity is create, the default activity manager behaviour is to create one
    /*if (this.activityField == null) {
        createActivity(FragmentActivity.class, null);
        androidUnitTest.activity().setActivityState(ActivityState.CREATED);
    }*/

    if (fragmentAnnotation.attached()) {
        String tag = fragmentAnnotation.tag();
        if (tag == null || tag.isEmpty()) {
            tag = fragment.getClass().toString();
        }
        addToActivity(getActivity(), fragment, tag);
    }
}
项目:astor    文件:SpyOnInjectedFieldsHandler.java   
@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;
}
项目:AndroidUnitTest    文件:AnnotationActivityManager.java   
public void createAndInitActivity(@Nullable Object target, Class activityClass, @Nullable RActivity activityAnnotation) {
    Activity activity = getAndroidUnitTest().activity().createAndInitActivity(activityClass, activityAnnotation);
    if (this.activityField != null && target != null) {
        new FieldSetter(target, this.activityField).set(activity);
    }
}
项目:AndroidUnitTest    文件:AnnotationActivityManager.java   
public void updateActivity(Object target) {
    new FieldSetter(target, this.activityField)
            .set(getAndroidUnitTest().getActivityController().get());
}
项目:mockito-cglib    文件:AcrossJVMSerializationFeature.java   
/**
 * Hack the <code>name</code> field of the given <code>ObjectStreamClass</code> with
 * the <code>newProxyClass</code>.
 * <p/>
 * The parent ObjectInputStream will check the name of the class in the stream matches the name of the one
 * that is created in this method.
 * <p/>
 * The CGLIB classes uses a hash of the classloader and/or maybe some other data that allow them to be
 * relatively unique in a JVM.
 * <p/>
 * When names differ, which happens when the mock is deserialized in another ClassLoader, a
 * <code>java.io.InvalidObjectException</code> is thrown, so this part of the code is hacking through
 * the given <code>ObjectStreamClass</code> to change the name with the newly created class.
 *
 * @param descInstance The <code>ObjectStreamClass</code> that will be hacked.
 * @param proxyClass   The proxy class whose name will be applied.
 * @throws InvalidObjectException
 */
private void hackClassNameToMatchNewlyCreatedClass(ObjectStreamClass descInstance, Class<?> proxyClass) throws ObjectStreamException {
    try {
        Field classNameField = descInstance.getClass().getDeclaredField("name");
        new FieldSetter(descInstance, classNameField).set(proxyClass.getCanonicalName());
    } catch (NoSuchFieldException nsfe) {
        // TODO use our own mockito mock serialization exception
        throw new MockitoSerializationIssue(join(
                "Wow, the class 'ObjectStreamClass' in the JDK don't have the field 'name',",
                "this is definitely a bug in our code as it means the JDK team changed a few internal things.",
                "",
                "Please report an issue with the JDK used, a code sample and a link to download the JDK would be welcome."
        ), nsfe);
    }
}
项目:astor    文件:AcrossJVMSerializationFeature.java   
/**
 * Hack the <code>name</code> field of the given <code>ObjectStreamClass</code> with
 * the <code>newProxyClass</code>.
 *
 * The parent ObjectInputStream will check the name of the class in the stream matches the name of the one
 * that is created in this method.
 *
 * The CGLIB classes uses a hash of the classloader and/or maybe some other data that allow them to be
 * relatively unique in a JVM.
 *
 * When names differ, which happens when the mock is deserialized in another ClassLoader, a
 * <code>java.io.InvalidObjectException</code> is thrown, so this part of the code is hacking through
 * the given <code>ObjectStreamClass</code> to change the name with the newly created class.
 *
 * @param descInstance The <code>ObjectStreamClass</code> that will be hacked.
 * @param proxyClass The proxy class whose name will be applied.
 * @throws InvalidObjectException
 */
private void hackClassNameToMatchNewlyCreatedClass(ObjectStreamClass descInstance, Class<?> proxyClass) throws ObjectStreamException {
    try {
      Field classNameField = descInstance.getClass().getDeclaredField("name");
      new FieldSetter(descInstance, classNameField).set(proxyClass.getCanonicalName());
    } catch (NoSuchFieldException nsfe) {
        // TODO use our own mockito mock serialization exception
        throw new MockitoSerializationIssue(join(
                "Wow, the class 'ObjectStreamClass' in the JDK don't have the field 'name',",
                "this is definitely a bug in our code as it means the JDK team changed a few internal things.",
                "",
                "Please report an issue with the JDK used, a code sample and a link to download the JDK would be welcome."
        ), nsfe);
    }
}