CodeBanga
CodeBanga

Reputation: 11

how to test crud operations in java

Please explain how I can test CRUD operations in java like these:

public void insert(User user) {
    Connection con = null;
    PreparedStatement ps;
    try {
        con = DatabaseConnection.dbCon();
        ps = con.prepareStatement("insert into usert (name,surname,role_id,login,password) values(?,?,?,?,?)");
        ps.setString(1, user.getName());
        ps.setString(2, user.getSurname());
        ps.setInt(3, user.getRole().getId());
        ps.setString(4, user.getLogin());
        ps.setString(5, user.getPassword());
        ps.execute();
        if (con != null) {
            con.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

/**
 * deletes user
 * @param user
 */
public void delete(User user) {
    Connection con = null;
    PreparedStatement ps;
    try {
        con = DatabaseConnection.dbCon();
        ps = con.prepareStatement("delete from usert where id = ?");
        ps.setInt(1, user.getId());
        ps.execute();
        if (con != null) {
            con.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

Now, I wrote unit tests for models like User and etc. I don't understand how to test buttons and another operations like above.

Upvotes: 1

Views: 2106

Answers (1)

Ivan Nikolaychuk
Ivan Nikolaychuk

Reputation: 257

Actually there are many drawbacks about your code. For example, you are trying to close a connection in 'try' block, instead of finally.

Anyway, up to your question. Note that my advice will make sence only if you are not using standard sql-syntaxis, common for all databases (it's ok for learning, but a rare situation in real-life). And unless you are learnin JDBC, I would also recomend you to take a look an ORM's like Hibernate.

For testing database-operations, you can do this:

  1. Create a non- static getConnection method, that triggers your DatabaseConnection.dbConn().
  2. Mock it using mockito library, providing some lightweight database like hsql.
  3. Do your tests

So, the logic of interracting with database will remain the same, the only thing that will cange is the storage.

BTW, there is no need to extract DatabaseConnection.dbConn() in a seperate method. You can use power-mock and it would work fine. But I recomend you to learn mockito first.

Upvotes: 1

Related Questions