Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public DBConnection(DBSource dbSource) { // <--- Constructor only required for test purposes :(
- this.dbSource = dbSource;
- }
- public final void createCompsDB() {
- Connection conn = null;
- Statement statement = null;
- try {
- if(dbSource==null){
- conn = DBSource.getInstance().getConnection();
- }else{
- conn = dbSource.getConnection(); /** Likely bad design, since dbSource is only NOT null for tests, so that you can inject the mocked datasource :( */
- }
- statement = conn.createStatement();
- statement.executeUpdate("CREATE DATABASE placesdb");
- System.out.println("Database created...");
- } catch (SQLException e) {
- // ...
- }
- } finally {
- // Close Resources...
- }
- }
- }
- public class DBConnectionTest {
- final Statement statement = mock(Statement.class);
- final Connection connection = mock(Connection.class);
- final DBSource dataSource = mock(DBSource.class);
- @Before
- public void setUp() throws SQLException, IOException, PropertyVetoException {
- when(dataSource.getConnection()).thenReturn(connection);
- when(connection.createStatement()).thenReturn(statement);
- }
- @Test
- public void testCreateCompDBIfNotAlready() throws Exception {
- DBConnection dbConnection = new DBConnection(localDB, dataSource); /** This constructor is only needed for testing :( . How do I avoid it since all the classes I need to test don't require the dependency to be injected? */
- dbConnection.createCompsDB();
- verify(statement).executeUpdate("CREATE DATABASE PLACES");
- }
- }
- protected DBSource() throws IOException, SQLException, PropertyVetoException {
- ds = new BasicDataSource();
- ds.setDriverClassName("org.postgresql.Driver");
- ds.setUsername("user");
- ds.setPassword("pass");
- ds.setUrl("jdbc:postgresql://localhost:5432/placesdb");
- }
- public static DBSource getInstance() { // <--- Static method means dependent classes don't need to accept injections
- if (datasource == null) {
- datasource = new DBSource();
- return datasource;
- } else {
- return datasource;
- }
- }
- public Connection getConnection() throws SQLException {
- return this.ds.getConnection();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement