How do I inject test objects when the real objects are created dynamically?
- by JW01
I want to make a class testable using dependency injection. But the class creates multiple objects at runtime, and passes different values to their constructor. Here's a simplified example:
public abstract class Validator {
private ErrorList errors;
public abstract void validate();
public void addError(String text) {
errors.add(
new ValidationError(text));
}
public int getNumErrors() {
return errors.count()
}
}
public class AgeValidator extends Validator {
public void validate() {
addError("first name invalid");
addError("last name invalid");
}
}
(There are many other subclasses of Validator.)
What's the best way to change this, so I can inject a fake object instead of ValidationError?
I can create an AbstractValidationErrorFactory, and inject the factory instead. This would work, but it seems like I'll end up creating tons of little factories and factory interfaces, for every dependency of this sort. Is there a better way?