Baral
Baral

Reputation: 3141

C# UnitTest ExpectedException

I created a custom attribute for unit testing based ExpectedExceptionBaseAttribute:

public class ExpectedEngineExceptionAttribute : ExpectedExceptionBaseAttribute

I override the Verify method as follow:

    protected override void Verify(Exception exception)
    {
        RethrowIfAssertException(exception);
        throw new Exception("Hola!!");
    }

Here's the TestMethod (It calls a method that throws a ):

    [TestMethod]
    [ExpectedEngineExceptionAttribute()]
    public void MyTest()
    {
        SomeCode();
    }

The output in the unit testing window just shows:

Exception has been thrown by the target of an invocation.

I would except to see the message Hola!!

When I run the following Test Method:

    [TestMethod]
    [ExpectedException(typeof(EngineException))]
    public void MyTest2()
    {
        SomeCode();
    }

The output is :

Test method NotificationInputAttributeInvalidTypeTest threw exception System.Exception, but exception EngineException was expected. Exception message: System.Exception: SS

What am I missing to have my "Hola" exception message to show in the output window?

I decompiled the ExpectedExceptionAttribute and did what it does in my custom attribute but it's not working...

UPDATE: Adding a breakpoint confirms the Exception("Hola!!") is thrown:

enter image description here

Upvotes: 1

Views: 2178

Answers (2)

Marco Medrano
Marco Medrano

Reputation: 3030

it is working perfectly in VS 2013 Update 2: enter image description here

The Code:

    [TestClass]
    public class MyTests
    {
       [TestMethod]
       [ExpectedEngineExceptionAttribute]
       public void MyTest()
       {
           throw new Exception("HI");
       }
     }

    public class ExpectedEngineExceptionAttribute : ExpectedExceptionBaseAttribute
    {
       protected override void Verify(Exception exception)
       {
           RethrowIfAssertException(exception);
           throw new Exception("Hola!!!");
       }
    }

Upvotes: 0

bowlturner
bowlturner

Reputation: 2016

The RethrowIfAssertException is throwing an exception when

"Throws the exception again if it is an AssertFailedException or an AssertInconclusiveException"

so if that is throwing an exception it will never get to your "Hola" exception throw.

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionbaseattribute.rethrowifassertexception.aspx

Upvotes: 1

Related Questions