Unit testing constructor injection
c#, constructor, constructor-injection, dependency-injection, unit-testing
Solution
Setting `this.service` is an implementation detail, so you should just be testing that it is used where expected and just test this via the `Start` method. Lest your tests become brittle.
You only want to test that your service is used appropriately. You shouldn't care how it is stored.
Problem
Suppose that my `Foo` class has the following: ``` readonly IService service; public Foo(IService service) { if (service == null) throw new ArgumentNullException("service"); this.service = service; } public void Start() { service.DoStuff(); } ``` So far, I have one unit test for the constructor where I pass in null to verify that an `ArgumentNullException` gets thrown. Do I need a second unit test for my constructor where I pass in a valid `IService` and verify that `this.service` gets set (which would require a public accessor)? Or should I just rely on my unit test for the `Start` method to test this code path?