tags

C# 8

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.