5

In the test below, if it enters the catch block I want to indicate that the test has passed. If the catch block is bypassed I want the test to fail.

Is there a way to do this, or am I missing the point with how tests should be structured?

[TestMethod]
public void CommandExecutionWillThrowExceptionIfUserDoesNotHaveEnoughEminence()
{
    IUserCommand cmd = CreateDummyCommand("TEST", 10, 10);
    IUser user = new User("chris", 40);

    try
    {
        cmd.Execute(user);
    }
    catch(UserCannotExecuteCommandException e)
    {
        //Test Passed
    }

    // Test Failed
}
Chris
  • 7,996
  • 11
  • 66
  • 98

4 Answers4

9

I tend to use this pattern when I have a similar situation:

// ...
catch (UserCannotExecuteCommandException e)
{
    return;    // Test Passed
}

Assert.Fail();    // Test Failed -- expected exception not thrown
Cameron
  • 96,106
  • 25
  • 196
  • 225
6

Declare the test to throw UserCannotExecuteCommandException, when that happens the test will succeed

[ExpectedException( typeof( UserCannotExecuteCommandException) )]
Orn Kristjansson
  • 3,435
  • 4
  • 26
  • 40
  • But does the test also succeed if the exception is *not* thrown? The OP needs the test to fail if no exception is thrown. – Cameron Dec 04 '11 at 04:51
  • Thanks for this. How do I prevent Visual Studio from stopping the execution of the tests when the actual exception is thrown? For example, I have to press F5/Continue before the test continues and can be marked as passed. – Chris Dec 04 '11 at 05:02
  • 2
    @Chris: Run the test *without* debugging (CTRL R, T) – Cameron Dec 04 '11 at 05:06
1

I would suggest using Assert.Throws() method:

Assert.Throws<UserCannotExecuteCommandException>() => cmd.Execute(user));

Id does all what you need. It expect that an exception of type UserCannotExecuteCommandException would be thrown whilst execution of the cmd.Execute() method, otherwise automatially marks a test as failed.

sll
  • 61,540
  • 22
  • 104
  • 156
0

Since [ExpectedException(...)] is concidered as a bad practice you might use:

  • MSTest: Assert.ThrowsException<UserCannotExecuteCommandException >( () => cmd.Execute(user) );
  • NUnit: Assert.Throws<UserCannotExecuteCommandException >( () => cmd.Execute(user) );

then you are able to point which line exactly should throw an exception.

J.Wincewicz
  • 849
  • 12
  • 19