0

Based on the example here, I tried to create a Unit Test for my method write() which basically take an object and save it into my SQLite DB.

I get this error:

enter image description here

These 2 lines have been commented with the word "ERROR" in my code below.

1) Connection with DB

public class DBAdapter {

    public Connection getConnection() throws WebApplicationException {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) 
            ctx.lookup("java:/comp/env/jdbc/escapeconnect");
            Connection con = ds.getConnection();
            Statement st = con.createStatement();
            st.execute("PRAGMA foreign_keys=on;");
            st.close();
            return con;
        } catch (NamingException e) {
            e.printStackTrace();
            throw new WebApplicationException(e.getMessage());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new WebApplicationException(e.getMessage());
        }       
    }
}

2) Class which take the object and insert it into the DB

public class DAOpanel implements DAOpanelIF {

    DBAdapter dbAdapter = new DBAdapter();

    @Override
    public int write(PanelDAOBean panel) {

        String query = "";

        if(panel.getId()<1) {
            query = "INSERT INTO panel (name,device_mac) VALUES(?,?)";

            try (Connection con = dbAdapter.getConnection();
                    PreparedStatement pstm = con.prepareStatement(query);){ // ERROR
                pstm.setString(1, panel.getName());             
                pstm.setString(2, panel.getDevice_mac());

                int rowsAffected = pstm.executeUpdate();
                if(rowsAffected==1) {
                    ResultSet rs = pstm.getGeneratedKeys();
                    if(rs.next()) {
                        return rs.getInt(1);
                    }
                }
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new WebApplicationException(e.getMessage());
            }
        }else {
            query = "UPDATE panel SET name = ?, device_mac = ? WHERE id = ?";

            try (Connection con = dbAdapter.getConnection();
                    PreparedStatement pstm = con.prepareStatement(query);){
                pstm.setString(1, panel.getName());             
                pstm.setString(2, panel.getDevice_mac());
                pstm.setInt(3, panel.getId());
                pstm.executeUpdate();
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new WebApplicationException(e.getMessage());
            }
        }
        return -1;
    }

3) Test of the method write() of the DAOpanel class

@ExtendWith(MockitoExtension.class)
class TestDaoPanel {

  PanelDAOBean panelForTest = new PanelDAOBean();

  @InjectMocks private DAOpanel daoPanel;

  @Mock private DBAdapter dbAdapter;

  @Mock private Connection con;

  @Mock private PreparedStatement pstm;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    panelForTest.setName("Panel Unit Test");
    panelForTest.setDevice_mac("FF:FF:FF:FF:FF:FF");

    when(con.prepareStatement(Mockito.any())).thenReturn(pstm);
    when(dbAdapter.getConnection()).thenReturn(con);
  }

  /**
   * Test method for {@link
   * main.java.ch.ffhs.pa5.escapeconnect.persistency.DAOpanel#write(PanelDAOBean)}.
   */
  @Test
  void testWrite() {
    daoPanel.write(panelForTest); // ERROR
  }

4) The object to be inserted into the DB

public class PanelDAOBean {
    private int id = 0;
    private String name;
    private String device_mac;
    public PanelDAOBean() {
        super();
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDevice_mac() {
        return device_mac;
    }
    public void setDevice_mac(String device_mac) {
        this.device_mac = device_mac;
    }

}

Thanks for your help.

1 Answers1

0

Your problem is on the following line

    public class DAOpanel implements DAOpanelIF {

        DBAdapter dbAdapter = new DBAdapter();
        ...
}

You are mocking DBAdapter but not injecting it into DAOpanel. You can just add a constructor that accepts DAOpanel

public class DAOpanel implements DAOpanelIF {
   priavte final DBAdapter dbAdapter;
   public DAOpanel(DBAdapter dbAdapter) {
      this.dbAdapter = dbAdapter;
   }
}

As you are using @Mock & @InjectMock, dependency will be automatically injected to constructor.

Yogesh Badke
  • 4,249
  • 2
  • 15
  • 23