How can I verify an exception was thrown with a certain parameter?

Suppose I have the following exception and method:

public MyException(string type)
{
    /* Does soemthing with the parameter */
}

public void DoSomething()
{
    // ...
    if (/* some rule */)
        throw new MyException("A");
    else
    {
        throw new MyException("B");
    }
}

I want to test my method, how can I verify using Visual Studio Unit Testing Framework that MyException with a specific parameter was thrown? I'd usually go with [ExpectedException(typeof(MyException)] but I wouldn't know which of these exceptions.

Jon Skeet
people
quotationmark

I'd usually go with [ExpectedException(typeof(MyException)]

I suggest you don't do that. You haven't told us which unit test framework you're using, but these days most provide something like:

Assert.Throws<MyException>(() => testSubject.DoSomething());

Aside from anything else, that will make sure the exception is only thrown where you expect it to be - not elsewhere.

Next, depending on your framework, you may find that Assert.Throws returns the exception thrown, so you can then validate things in that:

var exception = Assert.Throws<MyException>(...);
Assert.AreEqual("A", exception.Message);

Note that testing the exact message is generally pretty brittle - but if it's testing something else about the exception (e.g. ArgumentException.ParamName) that's more clear-cut.

people

See more on this question at Stackoverflow