So I find myself writing this code all the time:
[TestMethod]
[Description("Asserts that an ArgumentNullException is thrown if ResetPassword(null) is called")]
public void ResetPassword_Throws_ArgumentNullException_With_Null_Parameter( )
{
try
{
new MembershipServiceProvider( ).ResetPassword( null );
}
catch ( ArgumentNullException )
{
// ArgumentNullException was expected
Assert.IsTrue( true );
}
catch
{
Assert.Fail( "ArgumentNullException was expected" );
}
}
So instead of writing this code over and over I’d really like to create a method which accepts a Lambda expression which will execute the method in the try block.
Something like this:
public void AssertExpectedException( Action theAction ) where TException : Exception
{
try
{
// Execute the method here
}
catch ( TException )
{
Assert.IsTrue( true );
}
catch
{
Assert.Fail( string.Format( "An exception of type {0} was expected", typeof( TException ) ) );
}
}
So I can do something like this:
var provider = new MembershipServiceProvider();
AssertExpectedException(provider => provider.ResetPassword(null));
I’m really not sure if any of this is on the right track but hopefully someone can point me in the right direction.
Thanks
You’re almost there. Here’s what the test helper should look like:
And to call it:
Note the usage of
() => somethingwhich means the lambda has no parameters. You also have to specify the generic argument ofArgumentNullExceptionbecause the compiler cannot infer it.