0

For instance, insteead of

if (MyFancyObject is null)
    throw new InvalidOperationException();

I could simply say

Assert.IsNotNull(MyFancyObject);

But I hardly ever see this done - is there a good reason not to?

ekolis
  • 491
  • 1
  • 4
  • 7

3 Answers3

5

is there a good reason not to?

Yes: packaging.

There's nothing wrong with having code throw an AssertionError.

There's nothing wrong with wrapping the throw into some friendlier looking spelling, like Assert::isNotNull or Precondition::notNull.

But the few lines of typing you save creating this thing yourself are not worth the headaches of adding test packages to your dependency graph.

See also: LeftPad.

VoiceOfUnreason
  • 32,131
  • 2
  • 42
  • 79
2

If this is your convention, you lose the ability to catch specific exceptions.

Unit test methods tend to make certain assumptions about the environment that will not necessarily hold true in implementation code. For example, if I wanted to use this strategy in Python, now everything has to inherit from unittest.TestCase, and standalone functions are simply not an option anymore.

If you want something more concise for handling common error cases, easy enough to write your own utilities...

  • 1
    Assertions are used in C/C++ code to identify situations which should never happen, although they are removed at runtime. See https://www.geeksforgeeks.org/assertions-cc/ – Robert Harvey Jul 24 '19 at 18:45
  • @RobertHarvey I don't see the relevance? I would hope that a unittest library's assertion methods would not behave the same! –  Jul 24 '19 at 19:00
  • @RobertHarvey: C/C++ `assert` calls are not all that useful in unittesting. They terminate the application, including the testrunner. – Bart van Ingen Schenau Jul 25 '19 at 08:24
0

If your question is only adressing method input-parameter checking:

I prefer Assert.IsNotNull(MyFancyObject,"MyFancyObject null"); style because

  • it is less verbose
  • depending on the programming language: there are tools that can automatically remove these guard statements in release builds if you want. You cannot do this with the verbose style
k3b
  • 7,488
  • 1
  • 18
  • 31