tags

Argument Validation

Easy unit testing of null argument validation (C# 8 edition)

A few years ago, I blogged about a way to automate unit testing of null argument validation. Its usage looked like this: [Fact] public void FullOuterJoin_Throws_If_Argument_Is_Null() { var left = Enumerable.Empty<int>(); var right = Enumerable.Empty<int>(); TestHelper.AssertThrowsWhenArgumentNull( () => left.FullOuterJoin(right, x => x, y => y, (k, x, y) => 0, 0, 0, null), "left", "right", "leftKeySelector", "rightKeySelector", "resultSelector"); } Basically, for each of the specified parameters, the AssertThrowsWhenArgumentNull method rewrites the lambda expression by replacing the corresponding argument with null, compiles and executes it, and checks that it throws an ArgumentNullException with the appropriate parameter name.

Easy unit testing of null argument validation

When unit testing a method, one of the things to test is argument validation : for instance, ensure that the method throws a ArgumentNullException when a null argument is passed for a parameter that isn’t allowed to be null. Writing this kind of test is very easy, but it’s also a tedious and repetitive task, especially if the method has many parameters… So I wrote a method that automates part of this task: it tries to pass null for each of the specified arguments, and asserts that the method throws an ArgumentNullException.