Reputation: 11519
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?
Upvotes: 0
Views: 2856
Reputation: 4015
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.
Upvotes: 1
Reputation: 8101
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.
Upvotes: 4