Is it important to unit test a constructor?

C#.NetUnit TestingConstructor

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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.

Solution 4 - C#

No. Its functionality will be tested by every other unit test on the class.

Solution 5 - C#

You absolutely should test the constructor. If you have a default constructor, you should test that it can be called. What if later on the class is changed--perhaps it becomes a singleton or the default constructor is removed in favor of one requiring parameters? The test should fail in that case to alert that change (so that the class or the test can be fixed to meet the new requirement).

The presence of a default constructor is a requirement that should have a test. Even if all the constructor does is set private members that will be tested elsewhere, the fact that there is a parameterless constructor should be tested.

Solution 6 - C#

It depends.

I wouldn't bother writing a dedicated constructor test for something so simple as the example you gave.

However, if you have logical tests in the constructor such as a parameter validation, then yes, absolutely. Although, like the original poster, I do no work in the constructor if possible, it's common that parameter validation must be done. In this case it is unavoidable to keep the constructor from doing some work. If there's logic in the constructor, there's always the chance that it could be wrong, hence I treat it just like any other method call and test it appropriately.

Solution 7 - C#

I am testing constructors when they contain logic - e.g. validation or conditional setting a private state. Validation errors end up in an exception thrown from the constructor. Successful execution ends up in a creation of object which exhibits specific behavior depending on the state which was set in the constructor. In either way, it requires testing. But constructor tests are boring because they all look the same - invoke the constructor, make an assertion. Test method declarations often take more space than the whole testing logic... So I wrote a simple testing library which helps write declarative tests for the constructors: How to Easily Test Validation Logic in Constructors in C#

Here is an example in which I am trying seven test cases on a constructor of one class:

[TestMethod]
public void Constructor_FullTest()
{

    IDrawingContext context = new Mock<IDrawingContext>().Object; 

    ConstructorTests<Frame>
        .For(typeof(int), typeof(int), typeof(IDrawingContext))
        .Fail(new object[] { -3, 5, context }, typeof(ArgumentException), "Negative  length")
        .Fail(new object[] { 0, 5, context }, typeof(ArgumentException), "Zero length")
        .Fail(new object[] { 5, -3, context }, typeof(ArgumentException), "Negative width")
        .Fail(new object[] { 5, 0, context }, typeof(ArgumentException), "Zero width")
        .Fail(new object[] { 5, 5, null }, typeof(ArgumentNullException), "Null drawing context")
        .Succeed(new object[] { 1, 1, context }, "Small positive length and width")
        .Succeed(new object[] { 3, 4, context }, "Larger positive length and width")
        .Assert();

}

In this way, I can test all the relevant cases for my constructor without typing much.

Solution 8 - C#

In many FDA-regulated environments, more critical code must be 100% tested...including the construction of classes. So, the testing of constructors is sometimes necessary regardless of reasoning to or not to test them. Also, companies that use static analysis tools will need to make sure ALL data members of a class are properly initialized in order to not have errors although the code may run smoothly and free of errors. Usually data member initialization is done in the constructor...just food for thought.

Solution 9 - C#

I think the answer to this is "Yes".

There's plenty of code out there which assumes, horribly, an initialised object state, instead of a null reference - often when there are no explicit values assigned in the constructor.

I am happy to have constructor tests break to alert me when initialised public member values have been changed. This is about defensive testing - I'm pragmatic, and happier to have tests than not, and remove them when they're shown to not be helpful or useful.

Solution 10 - C#

I believe in 100% coverage. Also 100% coverage not by simply testing simple interactions by mocking things or just setting and getting things, but more integration/acceptance tests that check functionality. So if you end up writing really good integration/acceptance tests, all of your constructors (and simple methods such as setters and getters) should be called.

Solution 11 - C#

Testing accessors and mutators is also necessary unless the developer has ensured that no state logic can be changed. For instance, if one uses the design pattern for a Singleton, often times accessors or properties are used, and if the class is not initialized, it is done from the accessor since the constructor is private. In C++, one can make their functions const or static in which data members of the class cannot be changed. (Note: Even using static is a bit risky since those variables are often global.) However, without a test, if someone fails to use preventative measures, how can you guarantee with a 100% accuracy that what is written cannot become a failure over time? Maintenance is hardly foolproof.

Solution 12 - C#

What behavior of an instance of SystemInfo depends on the value of wrapper?

If anything can go wrong (e.g. null value causes breakage) then I suggest writing scenarios describing each such situation and using them to drive the definition of the appropriate unit tests.

If all of the scenarios end up being dependent on the state or behavior of the private instance of IMapinfoWrapper, then I'd suggest writing unit tests on that class instead.

Solution 13 - C#

Not unless you're writing a compiler, because you would only be testing that the compiler could generate code to do assignments, which is normally pointless.

Now, in a more usual situation, if you want to do something else with the wrapper, then maybe there's a point. For example, you could throw an ArgumentNullException if you tried to pass a null, and in theory, that could have a unit test. Even then, the value of the test is pretty minimal.

Personally, I almost never explicitly test constructors. If they are complicated enough to need tests, I tend to feel the code is a little on the smelly side.

Solution 14 - C#

If the constructor contains some logic, such as initialize a class, I think you should test the very constructor. Or you can talk to the developer that putting initialization in the constructor will cut the testability of code under test.

Solution 15 - C#

Unit Testing is about checking paths of execution, something often refered as Cyclomatic Complexity

If you have no path to choose from, no if, no loop, no GOTO (=P) its not very useful

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan WView Question on Stackoverflow
Solution 1 - C#yfeldblumView Answer on Stackoverflow
Solution 2 - C#Brian GenisioView Answer on Stackoverflow
Solution 3 - C#John SonmezView Answer on Stackoverflow
Solution 4 - C#DraemonView Answer on Stackoverflow
Solution 5 - C#c gView Answer on Stackoverflow
Solution 6 - C#Mark SimpsonView Answer on Stackoverflow
Solution 7 - C#Zoran HorvatView Answer on Stackoverflow
Solution 8 - C#BrandonView Answer on Stackoverflow
Solution 9 - C#badcop666View Answer on Stackoverflow
Solution 10 - C#digiarnieView Answer on Stackoverflow
Solution 11 - C#BrandonView Answer on Stackoverflow
Solution 12 - C#joel.neelyView Answer on Stackoverflow
Solution 13 - C#Jim CooperView Answer on Stackoverflow
Solution 14 - C#MagusView Answer on Stackoverflow
Solution 15 - C#EricView Answer on Stackoverflow