Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing constructor injection

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?

like image 857
markyd13 Avatar asked Apr 01 '13 20:04

markyd13


People also ask

Can we write unit test for constructor?

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.

What is a constructor injection?

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.

Should I use dependency injection in unit tests?

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.

Which is better setter or constructor injection?

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.


1 Answers

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.

like image 132
Justin Pihony Avatar answered Oct 19 '22 11:10

Justin Pihony