1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5package org.mockito.internal.configuration.injection.filter; 6 7import org.mockito.exceptions.Reporter; 8import org.mockito.internal.util.reflection.BeanPropertySetter; 9import org.mockito.internal.util.reflection.FieldSetter; 10 11import java.lang.reflect.Field; 12import java.util.Collection; 13 14/** 15 * This node returns an actual injecter which will be either : 16 * 17 * <ul> 18 * <li>an {@link OngoingInjecter} that do nothing if a candidate couldn't be found</li> 19 * <li>an {@link OngoingInjecter} that will try to inject the candidate trying first the property setter then if not possible try the field access</li> 20 * </ul> 21 */ 22public class FinalMockCandidateFilter implements MockCandidateFilter { 23 public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) { 24 if(mocks.size() == 1) { 25 final Object matchingMock = mocks.iterator().next(); 26 27 return new OngoingInjecter() { 28 public Object thenInject() { 29 try { 30 if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) { 31 new FieldSetter(fieldInstance, field).set(matchingMock); 32 } 33 } catch (RuntimeException e) { 34 new Reporter().cannotInjectDependency(field, matchingMock, e); 35 } 36 return matchingMock; 37 } 38 }; 39 } 40 41 return new OngoingInjecter() { 42 public Object thenInject() { 43 return null; 44 } 45 }; 46 47 } 48} 49