Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assertions when unit testing constructor?

I'm trying to unit test a class with 2 constructors. Each constructor has multiple parameters that set public properties. My question is, should I have only 2 unit tests with multiple asserts to check that each property was 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)
{}
like image 653
Kyle Russell Avatar asked Nov 29 '22 00:11

Kyle Russell


2 Answers

I've never been a fan of the dogma of "only a single assertion per test." It just doesn't seem practical to me - you end up with a lot of fluff (test declarations) around what you're actually interested in.

Yes, if you've got multiple issues you'll only have one test failure. You fix the test, run it again, spot the next failure, fix that and repeat until it succeeds. No great loss.

I'm not saying that you should be testing huge amounts of functionality in each test - but going to the other extreme isn't pragmatic either.

I would normally only go for one error condition per test though - so if your constructors would actually throw exceptions for null arguments, I'd check each of those in a separate test. It's easy to accidentally miss something otherwise.

like image 74
Jon Skeet Avatar answered Dec 16 '22 07:12

Jon Skeet


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

Therefore I would say 1 test per constructor, with multiple asserts on each, to ensure that all members are properly set.

like image 22
Mitchel Sellers Avatar answered Dec 16 '22 09:12

Mitchel Sellers