我正在尝试创建一个数据库连接库,以便在我的所有应用中使用。我想确保这个库完全经过单元测试,因此我尝试使用依赖注入。
我有这个课我想确保测试:
public class ConnectionFactory {
private String dataSourceName;
public ConnectionFactory(String dataSourceName) {
if(dataSourceName == null) {
throw new NullPointerException("dataSourceName can't be null");
}
this.dataSourceName = dataSourceName;
}
public Connection getConnection() throws SQLException {
Connection connection = getDataSource(dataSourceName).getConnection();
if(connection != null) {
return connection;
}
...
}
// Get a datasource object
private DataSource getDataSource(String dataSourceName) {
...
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("java:comp/env/" + dataSourceName);
} catch (NamingException e) {
...
}
return dataSource;
}
}
我希望能够通过简单的方式从我的所有应用程序中调用此类:
public class MyApp {
public static void main(string[] args) {
ConnectionFactory connectionFactory = new ConnectionFactory("jdbc/myDataSource");
Connection connection = connectionFactory.getConnection();
}
}
我已经开始为这个ConnectionFactory编写单元测试,但很快就意识到,使用我当前的代码,我无法模拟DataSource对象,因此它试图实际连接到真正的数据源。
@RunWith(Nested.class)
public class ConnectionFactoryTest {
public class Constructor {
@Test
public void shouldThrowNullPointerIfParamIsNull() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> { new ConnectionFactory(null); })
.withMessage("dataSourceName can't be null");
}
}
public class GetConnection {
public class WithDataSourceAvailable {
@Test
public void shouldErrorIfParamIsNull() {
ConnectionFactory connectionFactory = new ConnectionFactory("jdbc/myDataSource"); // <-- This is going to fail b/c it's trying to actually fetch a real data source
}
}
}
}
如何正确使用依赖注入,以便我可以编写实际上并未尝试连接数据源的单元测试?