Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AssertThrowsWhenArgumentNull: helper to test correct validation of null arguments
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");
}
}
}
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
You can’t perform that action at this time.