I have a User table and in UserController.java I have a method userList(); which returns all users from database using hibernate.
How can I write a JUnit test case for this piece of code. I am new to JUnit`.
Please help.
public List<User> userList() {
try
{
List <User> result = hibernateTemplate.find("from User");
return result;
}
finally {
//close the session and user-supplied JDBC connection
}
}
I suggest using spring-test, I’ve always found it very useful while doing database testing.
Simply setup an in memory database or a clean database (no data) only for testing.
Connect to it and setup your test with the @Rollback spring annotation.
This instructs the framework to rollback all changes done in the test after its done. This works 90% of the time if your application has a normal transactional behavior, if not you might need to write an @After method that does the db clean up for you.
Just insert a couple of users, do your retrieve and assert that the retrieved users and equal in number and properties of those that you inserted.