### Question:
JNDIConnectionFactory implements ConnectionFactory { public Connection getConnection(final String name) { try { final DataSource ds = (DataSource) context.lookup( convertIntoJndiName(name)); return ds.getConnection(); } catch (NamingException e) { throw new DatabaseException("Cannot obtain JNDI resource", e); } catch (SQLException e) { throw new DatabaseException("Cannot open connection", e); } } JNDIConnectionFactory(); Connection getConnection(final String name); @Override Connection getConnection(final String driver, final String url,
            final String username, final String password); static final String CONTAINER_PREFIX; }### Answer:
@Test public void getConnectionForExistingHook() throws Exception { expect(mockContext.lookup(eq("java:comp/env/hook"))) .andReturn(mockDataSource); expect(mockDataSource.getConnection()).andReturn(mockConnection); EasyMockUnitils.replay(); final Connection connection = factory.getConnection("hook"); assertSame("Unexpected connection returned", mockConnection, connection); }
@Test public void getConnectionWhenMissingHook() throws Exception { expect(mockContext.lookup(eq("java:comp/env/notexisting"))).andThrow( new NamingException("TEST")); EasyMockUnitils.replay(); try { factory.getConnection("notexisting"); fail("DatabaseException expected"); } catch (DatabaseException e) { } }
@Test public void getConnectionWhenDatasourceFails() throws Exception { expect(mockContext.lookup(eq("java:comp/env/jdbc/hook"))) .andReturn(mockDataSource); expect(mockDataSource.getConnection()).andThrow( new SQLException("TEST")); EasyMockUnitils.replay(); try { factory.getConnection("jdbc/hook"); fail("DatabaseException expected"); } catch (DatabaseException e) { } }
@Test public void getConnectionForFullyQualifiedHookName() throws Exception { expect(mockContext.lookup(eq("java:env/db/book"))).andReturn( mockDataSource); expect(mockDataSource.getConnection()).andReturn(mockConnection); EasyMockUnitils.replay(); final Connection connection = factory.getConnection("java:env/db/book"); assertSame("Unexpected connection returned", mockConnection, connection); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void createConnectionForParametersUnsupported() throws Exception { factory.getConnection("com.my.Driver", "jdbc:my: null, null); }