/******************************************************************************************************************* * * Returns the type of an object, taking care of mocks created by Mockito, for which the implemented interface is * returned. * * @param object the object * @return the object type * ******************************************************************************************************************/ @Nonnull /* VisibleForTesting */ static <T> Class<T> findTypeOf (final @Nonnull T object) { Class<?> ownerClass = object.getClass(); if (ownerClass.toString().contains("EnhancerByMockito")) { ownerClass = ownerClass.getInterfaces()[0]; // 1st is the original class, 2nd is CGLIB proxy if (log.isTraceEnabled()) { log.trace(">>>> owner is a mock {} implementing {}", shortName(ownerClass), shortNames(Arrays.asList(ownerClass.getInterfaces()))); log.trace(">>>> owner class replaced with {}", shortName(ownerClass)); } } return (Class<T>)ownerClass; } }
@Nonnull public static String shortNames (final @Nonnull Iterable<Class<?>> classes) { final StringBuilder result = new StringBuilder(); String separator = ""; for (final Class<?> clazz : classes) { result.append(separator).append(shortName(clazz)); separator = ", "; } return "[" + result.toString() + "]"; }
@Nonnull public static String shortId (final @Nullable Object object) { if (object == null) { return "null"; } String s = String.format("%s@%x", shortName(object.getClass()), System.identityHashCode(object)); if (object instanceof Identifiable) { s += "/" + ((Identifiable)object).getId(); } return s; }
/******************************************************************************************************************* * ******************************************************************************************************************/ @Test(dataProvider = "ownersAndRoleImplementations") public void must_correctly_find_roles (final @Nonnull Object owner, final @Nonnull Class<?> roleClass, final @Nonnull List<?> expectedRoles) throws NotFoundException { // given when(contextManager.findContextOfType(eq(Context1.class))).thenThrow(new NotFoundException()); when(contextManager.findContextOfType(eq(Context2.class))).thenReturn(context2); final UnderTest underTest = new UnderTest(); registerMockRoles(underTest); underTest.registerBean(bean1); underTest.registerBean(bean2); underTest.scan(asList(RI1A.class, RI1B.class, RI1C.class, RI2A.class, RI2B.class, RI2C.class, RI3A.class, RI3B.class, RI3C.class)); // when final List<?> actualRoles = underTest.findRoles(owner, roleClass); // then final String s = String.format("owner: %s role: %s", shortId(owner), shortName(roleClass)); assertListEquals(s, actualRoles, expectedRoles); }