For instance, insteead of

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

I could simply say


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

  • What do you expect the program to do if the assert fails?
    – mmmmmm
    Jul 24, 2019 at 18:35

3 Answers 3


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.


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 geeksforgeeks.org/assertions-cc Jul 24, 2019 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!
    – user214290
    Jul 24, 2019 at 19:00
  • @RobertHarvey: C/C++ assert calls are not all that useful in unittesting. They terminate the application, including the testrunner. Jul 25, 2019 at 8:24

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

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