How do I inject test objects when the real objects are created dynamically?

Posted by JW01 on Programmers See other posts from Programmers or by JW01
Published on 2011-01-31T20:14:46Z Indexed on 2011/01/31 23:33 UTC
Read the original article Hit count: 348

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?

© Programmers or respective owner

Related posts about unit-testing

Related posts about dependency-injection