How do I factor code to ease testability?
c++, tdd, unit-testing
Solution
If you only have one Engine type, why are you trying to make it a new object? If you don't plan on swapping engines, don't create another abstraction layer. Just make the engine part of the car.
You might be decomposing to reduce complexity, rather than to reuse components. Good call. In which case, I'd say that 3 is your best bet - validate your lower level components, then use higher level code that calls the lower level objects.
In reality, Engine is more likely to be something like Database. And you will want to change your constructors to use a different Database (for test reasons, or other reasons), but you can leave that lie for a while.
Problem
I am learning about Unit Testing and want to know how to write testable code. But, I'm not sure how to write testable code without making it complex. I'll take famous Car and Engine problem to describe the problem. ``` class Car { private: Engine m_engine; public: Car(); // Rest of the car } ``` I came up with following solutions to make the above code testable. Changing the Car's constructor to take Engine as a parameter. Then mock the Engine and do the testing. But, if I don't have different kinds of Engines, it seems inappropriate to parameterize the constructor just to make it testable. Using a setter and then pass a mock Engine to the setter. Same flow as the above. Testing the Engine first and then testing the Car with proven Engine (or using a stub Engine). What are the alternatives I have to make above code testable? What are the strenghts and weaknesses of each method?