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?
To test that a constructor does its job (of making the class invariant true), you have to first use the constructor in creating a new object and then test that every field of the object has the correct value. Yes, you need need an assertEquals call for each field.
Constructor Injection is the act of statically defining the list of required Dependencies by specifying them as parameters to the class's constructor. The constructor signature is compiled with the type and it's available for all to see.
Dependency injection helps if you have a class that needs a dependent class-instance to do some sub-processing. Instead of DI you can seperate the logic of a business-method into a data-gethering-part (that is not unit-testable) and a calculation part that can be unit-tested.
Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is a much bigger concern.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With