SystemJdbcDataSourceProvider { public synchronized DataSource getDataSource() { if (datasource == null) { datasource = lookupDataSource(); } return datasource; }  synchronized DataSource getDataSource();  }
@Test public void shouldLookUpTheDataSourceUsingTheCorrectJndiName() throws Exception { final String dataSourceName = "java:/app/framework/DS.system"; final DataSource dataSource = mock(DataSource.class); when(systemDataSourceNameProvider.getDataSourceName()).thenReturn(dataSourceName); when(initialContext.lookup(dataSourceName)).thenReturn(dataSource); assertThat(systemJdbcDataSourceProvider.getDataSource(), is(dataSource)); }
@Test public void shouldThrowExceptionIfTheLookupOfTheDataSourceFails() throws Exception { final NamingException namingException = new NamingException(); final String dataSourceName = "java:/app/framework/DS.system"; when(systemDataSourceNameProvider.getDataSourceName()).thenReturn(dataSourceName); when(initialContext.lookup(dataSourceName)).thenThrow(namingException); try { systemJdbcDataSourceProvider.getDataSource(); fail(); } catch (final JdbcRepositoryException expected) { assertThat(expected.getCause(), is(namingException)); assertThat(expected.getMessage(), is("Failed to lookup System DataSource using JNDI name 'java:/app/framework/DS.system'")); } }
@Test public void shouldOnlyLookupTheDataSourceOnce() throws Exception { final String dataSourceName = "java:/app/framework/DS.system"; final DataSource dataSource = mock(DataSource.class); when(systemDataSourceNameProvider.getDataSourceName()).thenReturn(dataSourceName); when(initialContext.lookup(dataSourceName)).thenReturn(dataSource); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); systemJdbcDataSourceProvider.getDataSource(); verify(systemDataSourceNameProvider, times(1)).getDataSourceName(); }