Let’s say I have a manager that looks something like this:
public class CustomerManager {
@Autowired
@Qualifier("customerDAO")
private CustomerDAO customerDAO;
public List<Customer> findCustomers() {
List<Customer> customers = customerDAO.findCustomers();
if (customers.size() == 0) {
// Do something else...
}
if (customers.size() == 1) {
// Do something else...
}
return customers;
}
}
Now a sample of how my test is configured:
public class CustomerManagerUnitTest extends AbstractDependencyInjectionSpringContextTests {
protected String[] getConfigLocations() {
return new String[] { "classpath:test-spring-customer.xml" };
}
public void testFindCustomers_NoResults() {
CustomerManager customerManager = new CustomerManager();
List<Customer> customers = customerManager.findCustomers();
// Test...
}
public void testFindCustomers_OneResult() {
CustomerManager customerManager = new CustomerManager();
List<Customer> customers = customerManager.findCustomers();
// Test...
}
public void testFindCustomers_MultipleResults() {
CustomerManager customerManager = new CustomerManager();
List<Customer> customers = customerManager.findCustomers();
// Test...
}
}
Depending upon the number of customers (or the type of customer data), I need to do something specific. I’m using Spring’s AbstractDependencyInjectionSpringContextTests in order to use test contexts. So getting a mock DAO from a test context config, and autowiring it is no problem. However, that means I would need to have a different context config and different mock DAOs for every test that requires testing a different result set. Right now you can see I only have one test config for my mock DAO. What is the best way to handle this?
Don’t let Spring create your CustomerManager to test. Create it by hand and inject a mock DAO manually. that’s the whole point of dependency injection: