Last active
July 20, 2017 20:24
-
-
Save thomaslevesque/c4cb9f537316b122f5b9 to your computer and use it in GitHub Desktop.
AssertThrowsWhenArgumentNull: helper to test correct validation of null arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using NUnit.Framework; | |
namespace MyLibrary.Tests.XEnumerableTests | |
{ | |
[TestFixture] | |
class FullOuterJoinTests | |
{ | |
[Test] | |
public void FullOuterJoin_Throws_If_Argument_Null() | |
{ | |
var left = Enumerable.Empty<int>().ForbidEnumeration(); | |
var right = Enumerable.Empty<int>().ForbidEnumeration(); | |
TestHelper.AssertThrowsWhenArgumentNull( | |
() => left.FullOuterJoin(right, x => x, y => y, (k, x, y) => 0, 0, 0, null), | |
"left", "right", "leftKeySelector", "rightKeySelector", "resultSelector"); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using NUnit.Framework; | |
namespace MyLibrary.Tests | |
{ | |
static class TestHelper | |
{ | |
public static void AssertThrowsWhenArgumentNull(Expression<TestDelegate> expr, params string[] paramNames) | |
{ | |
var realCall = expr.Body as MethodCallExpression; | |
if (realCall == null) | |
throw new ArgumentException("Expression body is not a method call", "expr"); | |
var realArgs = realCall.Arguments; | |
var paramIndexes = realCall.Method.GetParameters() | |
.Select((p, i) => new { p, i }) | |
.ToDictionary(x => x.p.Name, x => x.i); | |
var paramTypes = realCall.Method.GetParameters() | |
.ToDictionary(p => p.Name, p => p.ParameterType); | |
foreach (var paramName in paramNames) | |
{ | |
var args = realArgs.ToArray(); | |
args[paramIndexes[paramName]] = Expression.Constant(null, paramTypes[paramName]); | |
var call = Expression.Call(realCall.Method, args); | |
var lambda = Expression.Lambda<TestDelegate>(call); | |
var action = lambda.Compile(); | |
var ex = Assert.Throws<ArgumentNullException>(action, "Expected ArgumentNullException for parameter '{0}', but none was thrown.", paramName); | |
Assert.AreEqual(paramName, ex.ParamName); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment