2

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?

Bitfiddler
  • 3,942
  • 7
  • 36
  • 51

3 Answers3

2

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.

Chris Marinos
  • 965
  • 8
  • 8
0

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.

Sebastian Graf
  • 3,602
  • 3
  • 27
  • 38
0

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");

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44