How to test a method that returns all of the entities of a given type from the DB? [closed]
I have a method getAll
in my EmployeeDAO
class that fetches all the employees in the database and returns a List<Employee>
. How can I test this method?
public java.util.List<Employee> getAll() throws DataException;
Using the great FEST (look, their Hello World example also tests list of employees...) library you can write:
asseertThat(testList)
.hasSize(2)
.containsExactly(employee1, employee2);
The only problem with this code is that you must create employee1
and employee2
instance manually and assure that they have proper equals()
method. Maybe less verbose and more direct method is as follows:
asseertThat(testList)
.hasSize(2)
assertThat(testList.get(0).getEmployeeName())
.isEqualTo("John");
assertThat(testList.get(1).getEmployeeName())
.isEqualTo("Alice");
In both cases you have to take care of the order of items in returned collection. Since you are returning List
, user of your DAO might assume that the order is not random (by id
?)
Assuming you're using junit, setup HyperSQL (an in-memory db), load it with the desired tables and data. Then run your test and check if you get the correct data back. Note that if you're using lots of stored procedures and db vendor specific stuff this approach won't work.
This is the code I came up with:
//test the search method
EmployeeDAO testDAO = EmployeeDAO.getInstance();
List<Employee> testList = testDAO.getAll();
System.out.println(testList.size());
Thanks for the help!
精彩评论