PackageBasedClassFinder { public <T> Class<? extends T> findFirstOf(final Class<T> interfaceOrClass, final String packageName) throws ClassNotFoundException { Class<? extends T> result = null; Set<Class<? extends T>> classesThatImplementTheInterface = packageBasedClassFinderCore.find(packageName, interfaceOrClass); Iterator<Class<? extends T>> iterator = classesThatImplementTheInterface.iterator(); if (iterator.hasNext()) { result = getResult(iterator); } else { throw new ClassNotFoundException(String.format(CLASS_NOT_FOUND_TEMPLATE, interfaceOrClass.getName(), packageName)); } warnOfMultipleClasses(classesThatImplementTheInterface, packageName, interfaceOrClass); return result; }  Class<? extends T> findFirstOf(final Class<T> interfaceOrClass, final String packageName);  }
@Test public void testFindFirstOfShouldNotReturnNull() throws ClassNotFoundException { Set<Class<? extends Object>> value = new HashSet<>(); value.add(Object.class); given(packageBasedClassFinderCore.find(PACKAGE_NAME, INTERFACE_OR_CLASS)).willReturn(value); Class<? extends Object> result = underTest.findFirstOf(INTERFACE_OR_CLASS, PACKAGE_NAME); assertNotNull(result); }
@Test(expectedExceptions = ClassNotFoundException.class) public void testFindFirstOfShouldThrowClassNotFoundExceptionWhenNoClassIsFound() throws ClassNotFoundException { Set<Class<? extends Object>> value = new HashSet<>(); given(packageBasedClassFinderCore.find(PACKAGE_NAME, INTERFACE_OR_CLASS)).willReturn(value); underTest.findFirstOf(INTERFACE_OR_CLASS, PACKAGE_NAME); }
@Test public void testFindFirstOfShouldWarnIfMoreClassesAreFound() throws ClassNotFoundException { Set<Class<? extends Object>> value = new HashSet<>(); value.add(Object.class); value.add(String.class); given(packageBasedClassFinderCore.find(PACKAGE_NAME, INTERFACE_OR_CLASS)).willReturn(value); underTest.findFirstOf(INTERFACE_OR_CLASS, PACKAGE_NAME); String expected = String.format(MULTIPLE_CLASSES_FOUND_TEMPLATE, value, PACKAGE_NAME, INTERFACE_OR_CLASS); verify(logger).info(expected); }