### Question:
ExtensionObjectFactory { public <T> T newInstance(SpiExtensionFactory extensionFactory, Class<T> type) throws ExtensionLoadingException { try { Class<?> extensionClass = loadClass(extensionFactory); Object instance = extensionClass.newInstance(); return type.cast(instance); } catch (ExtensionLoadingException e) { throw e; } catch (Exception e) { throw new ExtensionLoadingException("error instantiating class=" + extensionFactory.factoryClass(), e); } } private  ExtensionObjectFactory(); @VisibleForTesting  ExtensionObjectFactory(Function<SpiExtensionFactory, ClassSource> extensionLocator); T newInstance(SpiExtensionFactory extensionFactory, Class<T> type); static final ExtensionObjectFactory EXTENSION_OBJECT_FACTORY; }### Answer:
@Test public void throwsAppropriateExceptionIfClassNotFound() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> name -> { throw new ClassNotFoundException(); }); Exception e = assertThrows(ExtensionLoadingException.class, () -> factory.newInstance(new SpiExtensionFactory("some.FakeClass", "/fake/class/path"), Object.class)); assertEquals("no class=some.FakeClass is found in the specified classpath=/fake/class/path", e.getMessage()); }
@Test public void throwsAppropriateExceptionIfObjectCannotBeInstantiated() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> DEFAULT_CLASS_LOADER); String className = CannotInstantiate.class.getName(); try { factory.newInstance(new SpiExtensionFactory(className, "/fake/class/path"), Object.class); fail("No exception thrown"); } catch (ExtensionLoadingException e) { assertThat(e.getMessage(), is("error instantiating class=" + className)); assertThat(e.getCause(), is(instanceOf(IllegalAccessException.class))); } }
@Test public void instantiatesObjects() { ExtensionObjectFactory factory = new ExtensionObjectFactory(extensionFactory -> DEFAULT_CLASS_LOADER); String className = String.class.getName(); Object object = factory.newInstance(new SpiExtensionFactory(className, "/fake/class/path"), Object.class); assertThat(object, is(instanceOf(String.class))); }