0

I have Customer class that make connection to db and save data to mysql. I use tomcat7 and mysql. I want to test this class. I have this method:

public CustomerData findById(int customerId) throws SQLException {
    Connection conn = null;
    PreparedStatement stmt = null;
    CustomerData customer = null;

    try {
        String sql = "SELECT id, status, username, email, age, country, city, is_hidden FROM "
                + TABLE + " WHERE  id = ?";

        conn = DBManager.getConnection();
        stmt = conn.prepareStatement(sql);

        stmt.setInt(1, customerId);

        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            customer = new CustomerData(rs.getInt(1), rs.getInt(2),
                    rs.getString(3), null, rs.getString(4), rs.getInt(5),
                    String.valueOf(rs.getInt(6)), String.valueOf(rs
                            .getInt(7)), 0, rs.getInt(8));
        }

        return customer;
    } finally {
        closeConnection(conn, stmt);
    }
}

How can I test it?

5
  • What do you want to test? There is hardly any logic in there. Commented Nov 26, 2011 at 10:47
  • I want to test sql syntax and returned data Commented Nov 26, 2011 at 10:48
  • if you want to test connection, you should test the DBManager. If you want to test CustomerData.findById and if you want to write a unit test, you should use mock object. Commented Nov 26, 2011 at 10:49
  • In this case, maybe mocking out the database connection (with a fake one that asserts the SQL string and returns a pre-arranged result set) would work. You'd need to make your DBManager support that, though. Commented Nov 26, 2011 at 10:51
  • I want to test CustomerData.findById. what I should mock? Commented Nov 26, 2011 at 10:51

2 Answers 2

4

You can test it just like you want to, i would recommend you create a seperate database though, seperating production and test data.

You should check out the article from dallaway, which is absolutely brilliant.

Sign up to request clarification or add additional context in comments.

Comments

1

you should have a db test with prepopulated data. You can call findById with a fixed customerId anche check the result against a some constants. Suppose you have a customer on test db with name "Test" registrationDate "10/10/2010" and Id 1 you could end with something like

CustomerData customer = yourclass.findById(1);
Assert.assertNotNull(customer);
Assert.assertEquals(customer.getId(),1);
Assert.assertEquals(customer.getName(),"Test");
Assert.assertEquals(customer.getRegistrationDate(),"10/10/2010");

where Assert class is one vailable from Junit o TestNG or you testing framework.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.