use of org.mockito.ScopedMock in project mockito by mockito.
the class IndependentAnnotationEngine method process.
@Override
public AutoCloseable process(Class<?> clazz, Object testInstance) {
List<ScopedMock> scopedMocks = new ArrayList<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
boolean alreadyAssigned = false;
for (Annotation annotation : field.getAnnotations()) {
Object mock = createMockFor(annotation, field);
if (mock instanceof ScopedMock) {
scopedMocks.add((ScopedMock) mock);
}
if (mock != null) {
throwIfAlreadyAssigned(field, alreadyAssigned);
alreadyAssigned = true;
final MemberAccessor accessor = Plugins.getMemberAccessor();
try {
accessor.set(field, testInstance, mock);
} catch (Exception e) {
for (ScopedMock scopedMock : scopedMocks) {
scopedMock.close();
}
throw new MockitoException("Problems setting field " + field.getName() + " annotated with " + annotation, e);
}
}
}
}
return () -> {
for (ScopedMock scopedMock : scopedMocks) {
scopedMock.closeOnDemand();
}
};
}
use of org.mockito.ScopedMock in project mockito by mockito.
the class MockitoExtension method resolveParameter.
@Override
@SuppressWarnings("unchecked")
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) throws ParameterResolutionException {
final Parameter parameter = parameterContext.getParameter();
Object mock = MockAnnotationProcessor.processAnnotationForMock(parameterContext.findAnnotation(Mock.class).get(), parameter.getType(), parameter::getParameterizedType, parameter.getName());
if (mock instanceof ScopedMock) {
context.getStore(MOCKITO).get(MOCKS, Set.class).add(mock);
}
return mock;
}
use of org.mockito.ScopedMock in project mockito by mockito.
the class InjectingAnnotationEngine method injectCloseableMocks.
/**
* Initializes mock/spies dependencies for objects annotated with
* @InjectMocks for given testClassInstance.
* <p>
* See examples in javadoc for {@link MockitoAnnotations} class.
*
* @param testClassInstance
* Test class, usually <code>this</code>
*/
private AutoCloseable injectCloseableMocks(final Object testClassInstance) {
Class<?> clazz = testClassInstance.getClass();
Set<Field> mockDependentFields = new HashSet<>();
Set<Object> mocks = newMockSafeHashSet();
while (clazz != Object.class) {
new InjectMocksScanner(clazz).addTo(mockDependentFields);
new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks);
onInjection(testClassInstance, clazz, mockDependentFields, mocks);
clazz = clazz.getSuperclass();
}
new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance);
return () -> {
for (Object mock : mocks) {
if (mock instanceof ScopedMock) {
((ScopedMock) mock).closeOnDemand();
}
}
};
}
Aggregations