Advertisement
Guest User

Untitled

a guest
Jan 6th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. public DBConnection(DBSource dbSource) { // <--- Constructor only required for test purposes :(
  2. this.dbSource = dbSource;
  3. }
  4.  
  5. public final void createCompsDB() {
  6. Connection conn = null;
  7. Statement statement = null;
  8. try {
  9. if(dbSource==null){
  10. conn = DBSource.getInstance().getConnection();
  11. }else{
  12. conn = dbSource.getConnection(); /** Likely bad design, since dbSource is only NOT null for tests, so that you can inject the mocked datasource :( */
  13. }
  14. statement = conn.createStatement();
  15. statement.executeUpdate("CREATE DATABASE placesdb");
  16. System.out.println("Database created...");
  17. } catch (SQLException e) {
  18. // ...
  19. }
  20. } finally {
  21. // Close Resources...
  22. }
  23. }
  24. }
  25.  
  26. public class DBConnectionTest {
  27. final Statement statement = mock(Statement.class);
  28. final Connection connection = mock(Connection.class);
  29. final DBSource dataSource = mock(DBSource.class);
  30.  
  31. @Before
  32. public void setUp() throws SQLException, IOException, PropertyVetoException {
  33. when(dataSource.getConnection()).thenReturn(connection);
  34. when(connection.createStatement()).thenReturn(statement);
  35. }
  36.  
  37. @Test
  38. public void testCreateCompDBIfNotAlready() throws Exception {
  39. 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? */
  40. dbConnection.createCompsDB();
  41. verify(statement).executeUpdate("CREATE DATABASE PLACES");
  42. }
  43. }
  44.  
  45. protected DBSource() throws IOException, SQLException, PropertyVetoException {
  46. ds = new BasicDataSource();
  47. ds.setDriverClassName("org.postgresql.Driver");
  48. ds.setUsername("user");
  49. ds.setPassword("pass");
  50. ds.setUrl("jdbc:postgresql://localhost:5432/placesdb");
  51. }
  52.  
  53. public static DBSource getInstance() { // <--- Static method means dependent classes don't need to accept injections
  54. if (datasource == null) {
  55. datasource = new DBSource();
  56. return datasource;
  57. } else {
  58. return datasource;
  59. }
  60. }
  61.  
  62. public Connection getConnection() throws SQLException {
  63. return this.ds.getConnection();
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement