How does ExpectedException attribute work in Visual Studio 2010 Unit Testing

Answered How does ExpectedException attribute work in Visual Studio 2010 Unit Testing

  • Thursday, August 16, 2012 7:13 AM
     
      Has Code

    Hi friends,

    I'm new to Visual Studio Unit Testing. I have a doubt that what actually [ExpectedException()] attribute does.
    AreSame has passed when ExpectedException attribute not provided ,but if i provide ExpectedException attribute then it fails without AssertFailedException.

    Result Passed Code :

    [TestMethod()]
    public void getMyNameTest()
    {
     string expected = "Hi";
     string actual = "Hi";
     Assert.AreSame(expected, actual);
    }

    Here i'm getting result as Pass

     

    Result Failed Code :

    [TestMethod()]
    [ExpectedException(typeof(System.NullReferenceException))]
    public void getMyNameTest()
    {
     string expected = "Hi";
     string actual = "Hi";
     Assert.AreSame(expected, actual);
    }

    Here i'm getting result as "Failed"

    So, i just wanna what actually expected exception does, please guide me friends..

     


    Thanks - Ravi

All Replies

  • Thursday, August 16, 2012 8:32 AM
    Moderator
     
     Answered

    Hi Ravi,

    Thank you for posting in the MSDN forum.

    When you want the test method to verify that an exception you expected to be thrown by a method in your development code, you can decorate a test method with the ExpectedExceptionAttribute. The ExpectedExceptionAttribute indicates that an exception is expected during test method execution.  And the test method will pass if the expected exception is thrown. The test will fail if the thrown exception inherits from the expected exception. In your situation, as no exception was thrown, the test failed.

    I hope this will be helpful to you.

    Best regards,


    Amanda Zhu [MSFT]
    MSDN Community Support | Feedback to us

    • Marked As Answer by Ravi exact Friday, August 17, 2012 4:49 AM
    •