ComponentProxyObjectFactory { protected <T extends Object> T getBean(String beanName, Class<T> type) { Object proxyObject = null; ApplicationContext workingContext = getContext(); if (workingContext != null) { proxyObject = workingContext.getBean(beanName); } else { LOG.warn("ApplicationContext was null - not retrieving bean."); } return type.cast(proxyObject); }    }
@Test public void testGetBeanHappy() { try { final String testBean = "testbean"; final ApplicationContext appContext = new FileSystemXmlApplicationContext() { @Override public Object getBean(String beanName) { return testBean; } }; ComponentProxyObjectFactory sut = new ComponentProxyObjectFactory() { @Override protected ApplicationContext getContext() { return appContext; } @Override protected String getConfigFileName() { return ""; } }; assertEquals("getBean test value", "testbean", sut.getBean("", String.class)); } catch (Throwable t) { System.out.println("Error running testGetBeanHappy test: " + t.getMessage()); t.printStackTrace(); fail("Error running testGetBeanHappy test: " + t.getMessage()); } }
@Test public void testGetBeanNullContext() { try { ComponentProxyObjectFactory sut = new ComponentProxyObjectFactory() { @Override protected ApplicationContext getContext() { return null; } @Override protected String getConfigFileName() { return ""; } }; assertNull("ApplicationContext from getContext", sut.getBean("", String.class)); } catch (Throwable t) { System.out.println("Error running testGetBeanNullContext test: " + t.getMessage()); t.printStackTrace(); fail("Error running testGetBeanNullContext test: " + t.getMessage()); } }
@Test public void testGetBeanWrongType() { try { final String testBean = "testbean"; final ApplicationContext appContext = new FileSystemXmlApplicationContext() { @Override public Object getBean(String beanName) { return testBean; } }; ComponentProxyObjectFactory sut = new ComponentProxyObjectFactory() { @Override protected ApplicationContext getContext() { return appContext; } @Override protected String getConfigFileName() { return ""; } }; sut.getBean("", Integer.class); fail("Should have had exception."); } catch (ClassCastException cce) { assertTrue(true); } catch (Throwable t) { System.out.println("Error running testGetBeanWrongType test: " + t.getMessage()); t.printStackTrace(); fail("Error running testGetBeanWrongType test: " + t.getMessage()); } }