Details
-
Bug
-
Status: Closed
-
Major
-
Resolution: Fixed
-
Testing OSGi Mock 2.4.10
-
None
Description
When trying to inject references to fields that are of type collection, the injection fails, due to the following isAssignableFrom check in the code below:
private static Field getFieldWithAssignableType(Class clazz, String fieldName, Class<?> type) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (StringUtils.equals(field.getName(), fieldName) && field.getType().isAssignableFrom(type)) { return field; } } }
The type parameter is always Collection.class, and the field.getType() is a subclass of Collection, such as Set or List. The problem is that the check is inverted, e.g. Set.class.isAssignableFrom(Collection.class) is false, whereas Collection.class.isAssignableFrom(Set.class) is true. The least specific class type should be first, opposite of the instanceof check ( I always find this confusing ).
I have prepared a simple patch, but unfortunately the build fails with MockBundleContextDynamicReferencesOsgiR6Test.testReferenceWithDynamicTargetFilter:172->assertDependencies3DynamicFiltered:209 expected:<dependency3b> but was:<null>.
I am not familiar enough with the codebase to understand whether I should update the test or try and find out what breaks.
The patch I tried is:
diff --git a/core/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java b/core/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java index 8726f9d..71b7e9a 100644 --- a/core/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java +++ b/core/src/main/java/org/apache/sling/testing/mock/osgi/OsgiServiceUtil.java @@ -340,7 +340,7 @@ final class OsgiServiceUtil { private static Field getFieldWithAssignableType(Class clazz, String fieldName, Class<?> type) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { - if (StringUtils.equals(field.getName(), fieldName) && field.getType().isAssignableFrom(type)) { + if (StringUtils.equals(field.getName(), fieldName) && type.isAssignableFrom(field.getType())) { return field; } }