Yes, and that’s pretty straight forward. You can pass a Actiondelegate (or indeed any type of delegate) to a method and call it:
void TestExceptionMessage(Action action, string message)
{
try
{
action();
Assert.Fail("No exception thrown");
}
catch (ApplicationException e)
{
StringAssert.StartsWith(e.Message, message);
}
}
This delegate can be a reference to a method or it can be a lambda expression as follows:
var x = new MyClass();
TestExceptionMessage(() => x.Method(123, "test"),"Oh no!");
, (, , ), Expression<Action>
void TestExceptionMessage(Expression<Action> expression, string message)
{
try
{
var methodName = (expression.Body as MethodCallExpression)?.Method.Name;
if (methodName != null)
{
Debug.WriteLine($"Calling {methodName}");
}
expression.Compile().Invoke();
Assert.Fail("No exception thrown");
}
catch (ApplicationException e)
{
StringAssert.StartsWith(e.Message, message);
}
}
:
var x = new MyClass();
TestExceptionMessage(() => x.Method(123, "test"),"Oh no!");