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?