basically, I've created a custom Assert method that asserts that an exception was thrown. It's a convenience for some unit testing I'm doing
Except it takes an Action as a parameter (obviously) but won't take a property assignment as an action.
How do I wrap the property assignment in an anonymous function?
public static class AssertException
{
public static void DoesntThrow<T>(Action func) where T : Exception
{
try
{
func.Invoke();
}
catch (Exception e)
{
Assert.Fail("No exception was expected but exception of type "
+ e.GetType() + " with message " + e.Message + " was thrown");
}
}
public static void Throws<T>(Action func, string expectedMessage = "") where T : Exception
{
bool exceptionThrown = false;
try
{
func.Invoke();
}
catch ( Exception e )
{
Assert.IsTrue(e.GetType() == typeof(T), "Expected exception of type " + typeof(T)
+ " but type of " + e.GetType() + " was thrown instead");
if (!expectedMessage.Equals(""))
{
Assert.AreEqual(e.Message == expectedMessage, "Expected exception with message of "
+ expectedMessage + " but exception with message " + e.Message + " was thrown instead");
}
return;
}
Assert.Fail("Expected exception of type " + typeof(T) + " but no exception was thrown");
}
}
And the call:
AssertException.DoesntThrow<Exception>(robot.Instructions = "RLRLMLR");
This is giving me:
Error 2 The best overloaded method match for 'RobotWarsTests.AssertException.DoesntThrow<System.Exception>(System.Action)' has some invalid arguments C:\Users\User\Documents\Visual Studio 2012\Projects\RobotWars\RobotWarsTests\UnitTest1.cs 20 13 RobotWarsTests
This creates a lambda expression that takes no parameters
()
and executes the code inside the curly braces.