98

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.

0

15 Answers 15

117

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.

4
  • 48
    If your constructor has, for example, an if (condition), you need to test both flows (true,false). If your constructor does some kind of job before setting. You should check the job is done.
    – graffic
    Jun 25, 2010 at 9:20
  • 2
    What if you have a checkArgumnt in the constructor (maybe to test the object is null or not)? Is it worth testing that?
    – noMAD
    Nov 4, 2014 at 22:31
  • 1
    Yes, it is often worth testing constructors with their own complex behavior.
    – yfeldblum
    Nov 5, 2014 at 22:46
  • I know I'm late to this party - but generally speaking I don't see constructors as a good place to put logic or validations in. Instead using for example some kind of request validators against your class operations could make more sense to me. Even though we should check the null reference in a constructor but yet I don't see a point in unit testing that, why? because your operation should fail if that object is null which makes sense the "behavior" fails and we should unit test that rather the actual constructors.
    – Ali
    Jul 24, 2019 at 9:34
59

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.

2
  • 8
    I never put any logic in my constructors. Just setters.
    – Nathan W
    Dec 10, 2008 at 23:11
  • @BrianGenisio, thanks for the tip, I just added some ArgumentNullException tests and code to my app...for some reason, never had it...
    – CaffGeek
    May 15, 2012 at 16:37
16

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.

12

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

1
  • 15
    Not every, if there are several constructors or several control flows inside it. Aug 12, 2010 at 9:44
9

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.

2
  • This is an old threat but I totally agree, the default constructor should be tested, and other constructors should be tested to give desired behavior when required arguments are missing. With Dependency Injection, it's very possible the default constructor could cause a circular loop of dependencies, which you'll never see if you never use the default constructor. Feb 10, 2019 at 5:01
  • All of the examples up there (except maybe changing to a singleton, but in that case there shouldn't even be a public default constructor to test) are things that will result in a compiler error. There's not just no need to test a logic-less constructor with a unit test, but doing so is an actual waste of time and money. If a constructor has logic though (other than simply setting properties), then it should absolutely be tested. Also @EtienneCharland a default constructor by definition has no dependencies (no parameters at all), so it can't create a circular dependency loop.
    – Tyler W
    Nov 8, 2019 at 21:42
6

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.

1
  • One of the better answers in the sense that the example given in the question is not a good one. A better question would have been: when is it appropriate to unit test a constructor? Feb 8, 2022 at 4:02
5

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.

3

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.

1
  • 1
    do you have a reference for the FDA requirement?
    – Ryan_S
    Feb 25, 2016 at 22:51
2

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.

1
  • why to delete them if they're already written? Dec 20, 2021 at 6:17
1

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.

5
  • 2
    100% coverage is a pipe dream and anyone who tells you differently is selling you a shiny new testing tool. ;) I kid... kind of. Dec 11, 2008 at 1:58
  • 1
    It might be a problem on legacy systems but if you're starting a new project from scratch, in my opinion 100% is the only way to go. I have worked on systems with 100% coverage. We test drove everything.
    – digiarnie
    Dec 12, 2008 at 5:45
  • OK, you had 100% coverage. But did you test all execution paths? The first doesn't imply the second.
    – kdgregory
    Dec 12, 2008 at 13:15
  • True 100% could easily be achieved with tests that do nothing but stub things out & test at a microlevel. But 100% coverage with tests that you believe to be the system's funct. paths will give you greater confidence with maintenance or new work even if not every execution path is accounted for.
    – digiarnie
    Dec 12, 2008 at 23:51
  • 4
    100% coverage of that you believe to be the system's functional paths. in other words: not 100%
    – ChatGPT
    Oct 30, 2012 at 17:52
1

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.

0

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.

0

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.

0

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.

-1

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

2
  • 3
    I don't agree with you that testing a method without any ifs/loops/gotos doesn't make sense. There is always at least one path of execution, and you should test it even if it is the only one. Dec 11, 2008 at 0:08
  • Eric, what about testing boundary cases--and testing representative values between the boundaries. For example, inputs of 0 and 1 might be considered boundary cases for a square root function, because there the input and output values are equal. So test, for example, -10, -1, -0.5, 0, 0.5, 1, and 10. Or also testing across the range. If your function should work for inputs up to 4096, try 4095 and 4097...
    – ChatGPT
    Oct 30, 2012 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.