A few statements when the constructor of testing units?

I am trying a unit test class with 2 constructors. Each constructor has several parameters that set public properties. My question is, should I have only 2 test blocks with several statements to verify that each property has been set OR a test for each parameter for each constructor?

Public Person(string name, string phone, string birthday) { name = name; phone = phone; birthday = birthday; } Public Person(string name) : this(name, null, null) {} 
+4
source share
4 answers

The operation you are testing is that the constructor accepts the __ parameters and that the values ​​are set to the correct value.

Therefore, I would say 1 test for each constructor with several statements on each, to make sure that all members are correctly set.

+8
source

I have never been a fan of the "only one statement per test" dogma. It just doesn't seem practical to me - in the end, you get a lot of fluff (test ads) around what you are really interested in.

Yes, if you have several problems, you will only have one test failure. You fix the test, run it again, mark the next failure, fix it and repeat until it succeeds. No big losses.

I'm not saying that you should test a huge amount of functionality in each test, but moving to the other extreme is also not pragmatic.

Usually I would use only one error condition for the test, so if your constructors actually threw exceptions for null arguments, I would check each of them in a separate test. It is easy to accidentally miss something otherwise.

+12
source

You might be interested to know what Kent Beck said right here on Stack Overflow. He said...

I get paid for code that works, not for tests, so my philosophy is to check as little as possible to achieve a given level of trust (I suspect that this level of trust is high compared to industry standards, but it might just be arrogance). If I don’t make any mistake at all (for example, setting the wrong variables in the constructor), I don’t check this. I, as a rule, make sense of test errors, therefore I am superfluous cautiously when I have logic with complex conventions. When coding in a team, I change my strategy to carefully check the code, which together we tend to make mistakes.

Here is the link.

I have no problem assuming that made me rethink some of the things that I did. And for the better.

+6
source

Secondly, the recommendation is not to have one test for each property, but one test with several statements for each constructor.

I would add that depending on where the yor class will be used, you may also have a test to test the behavior of your constructor when the name parameter is an empty string (negative testing).

0
source

All Articles