0

I have the following test:

    [Test]
    public void Save_WhenExceptionIsThrown_ThenExceptionIsLogged()
    {
        A.CallTo(() => this.personRepository.Save(A<PrsPerson>._)).Throws(new Exception("Expected Exception"));

        var personen = this.GetPersonenCollectionWithSpecificAmount(2);

        this.testee.Save(personen);

        A.CallTo(() => this.applicationLogger.Error(A<string>._)).MustHaveHappened(Repeated.Exactly.Once);
    }

This works like a charm, but what I want to assert additionally is, whether the logger was called with exactly the message of the thrown exception and not just any string.

Is it possible to capture the exception thrown and if so, how?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
xeraphim
  • 4,375
  • 9
  • 54
  • 102

2 Answers2

3

Specify you desired argument value explicitly inside method call lambda.

Try following

 A.CallTo(() => this.applicationLogger.Error("Expected Exception"))
 .MustHaveHappened(Repeated.Exactly.Once);
tchelidze
  • 8,050
  • 1
  • 29
  • 49
  • hey thanks for the answer. I don't want to hardcode the string. i want to be able to set the assert to: `A.CallTo(() => this.applicationLogger.Error(ex.Message)).MustHaveHappened(Repeated.Exactly.Once);` where exc is the thrown exception – xeraphim Mar 10 '16 at 08:21
  • 1
    Then I think your best approach is `var ex = new Exception("Expected Exception"); A.CallTo(() => this.personRepository.Save(A._)).Throws(ex); /* … */ A.CallTo(() => this.applicationLogger.Error(ex.Message)).MustHaveHappened(Repeated.Exactly.Once); ` Capturing the string is possible, but more work, and I think this would work as well and read better. – Blair Conrad Mar 10 '16 at 11:42
1

Is the logger injected? You can mock it.

class ListLogger : List<string>, ILogger
{
    public void LogException(Exception ex)
    {
        Add(ex.ToString());
    }
}

Then after the test "acts" you can see if the expected exception is in the list.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62