简体   繁体   中英

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)
{}

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.

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.

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

I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don't typically make a kind of mistake (like setting the wrong variables in a constructor), I don't test for it. I do tend to make sense of test errors, so I'm extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong.

Here's the link.

I have no problem admitting that made me re-think some things I was doing. And for the better.

I second the recommendation of not having one test per property, but one test with several asserts for each constructor.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM