Hoborg
Hoborg

Reputation: 961

How to test a class hidden by its factory?

Context. I have interface IVehicle, class VehiclesFactory and private class Vehicle nested in the VehiclesFactory. Thus all code except the VehiclesFactory kwnows nothing about any implementations of the IVehicle.

Question. How should I unit test the Vehicle? And should I do it at all?

Assumption 1. I can make the Vehicle public. However this will allow the all code to write new VehiclesFactory.Vehicle(...) which I try to avoid.

Assumption 2. I can make a new public method in the VehiclesFactory, e. g., IVehicle ForUnitTests_Vehicle(...) which just calls the Vehicle constructor and passes its arguments to that constructor (allowing a unit test to supply necessary mocks). However this will allow the all code to call this strange method.

Assumption 3. Factories is a plague; use the new operator everywhere. However this will couple my code more tightly.

Upvotes: 0

Views: 71

Answers (1)

Maksym Strukov
Maksym Strukov

Reputation: 2689

How should I unit test the Vehicle?

You can use reflection to create an instance of Vehicle class in your test project or make your Vehicle class internal and use InternalsVisibleToAttribute attribute to make it visible to your test project. Though switching from private to internal will make your class visible to all the code in the same project, so I'm not sure if it's acceptable for you.

And should I do it at all?

Up to you, if it contains application critical logic probably you should test it.

Upvotes: 1

Related Questions