I have an interface and implementation class, and I'm using dependency injection in the construction of the class:
class House {
public:
virtual void blah() = 0; //etc. all the interface of my class
};
class HouseImpl : public House {
protected:
Door *front_door;
public:
HouseImpl(Door *door) : front_door(door) {}
};
Now, in my factory method or whatever method is actually building the class and its dependencies, do I pass in the dependencies, or create them on the fly?
Option 1
By passing in the dependency, my unit test can use the same factory to pass in a mock object and my test is written against the interface only.
House* get_house(Door* door) {
return new HouseImpl(door);
}
void unit_test_method_on_house() {
MockDoor mock_door;
House* class_under_test = get_house(mock_door);
}
In this approach, I'm thinking of my factory method as basically an abstraction of the constructor for my interface type. The downside I see is that as I add dependencies, they all must be added to the factory method signature, which really just passes the buck to the clients.
Option 2
The alternative is that the factory is what is used in production code, and the unit test instantiates the implementation class directly.
House* get_house() {
return new HouseImpl(new Door()); //ignore the memmory management details here
}
void unit_test_method_on_house() {
MockDoor mock_door;
HouseImpl class_under_test(mock_door);
}
The concern here is that I'm opening the unit test up to depending on the implementation class rather than depending on the interface only. Obviously, I could just be very careful to write good tests that don't make implementation specific assumptions, but on a large project, I don't want to assume that all developers will be as careful as me.
So, what's the recommended approach here?