Is it important to unit test a constructor?
Ought I to unit test constructors? Say I have a constructor like this:
IMapinfoWrapper wrapper;
public SystemInfo(IMapinfoWrapper mapinfoWrapper)
{
this.wrapper = mapinfoWrapper;
}
Do I need to write a unit test for this construtor? I don't have any getters for the wrapper variable, so I don't need to test that.
Solution 1:
Unit testing is about testing the public states, behaviors, and interactions of your objects.
If you simply set a private field in your constructor, what is there to test?
Don't bother unit-testing your simple accessors and mutators. That's just silly, and it doesn't help anyone.
Solution 2:
Yes. If you have logic in your constructor, you should test it. Simply setting properties is not logic IMO. Conditionals, control flow, etc IS logic.
Edit: You should probably test for when IMapinfoWrapper is null, if that dependency is required. If so, then that is logic and you should have a test that catches your ArgumentNullException or whatever... your tests are specifications that define how the code behaves. If it throws an ArgumentNullException, then that should be specified in a test.
Solution 3:
Q: If you are setting a member variable in the constructor, why are you setting it.
A: Because you have a failing unit test that can only be made to pass by setting it in the constructor.
If you use this logic, where you only write code to cause a unit test to pass (Test Driven Development), then you will already have the answer to your question.