Question

In my 'act' I want to capture an exception so that I can do multiple tests on the exception data. Examples on the web show how to capture and compare the type/message within a test (or 'It' block) but not how to capture the exception as an 'act' in itself.

I am currently just doing a try/catch within the 'act' body and storing the exception within the context for later testing in the 'It' block. There I can perform a number of different fluent assertions on the data. Is this the best approach?

Was it helpful?

Solution

Actually, there is indeed a better way to do this:

void describe_some_exceptional_behavior()
{
    context["when throwing an exception"] = () =>
    {
        act = () => throw new InvalidOperationException();

        it["should raise the exception"] = expect<InvalidOperationException>();
    };
}

Note: you assign the result of expect directly to it. This tripped me up the first time.

See the nspec specs for more examples.

OTHER TIPS

I don't think there currently is another way to achieve that apart from manual try catch blocks for storing the exception and later checking on it in an it block.

If you're willing to use an open-source framework, you could use Fluent Assertions and do this:

Action act = () => subject.Foo2("Hello");

act.ShouldThrow() .WithInnerException() .WithInnerMessage("whatever");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top