Search code examples
unit-testingnunitnunit-3.0

NUnit: Log test steps and assert description on test failure or error


On test failure Nunit will only show evaluated expected and actual conditions. There is no way to tell which Assert failed if you have multiple asserts

Expected: True
But was: False

Same issue on exceptions: there is a stack trace but its not that descriptive, and does not tell me any details of the steps occurred right before the error.

One way to do it is to pass messages to Assert or add log statements (e.g. using TestContext.WriteLine). But this means that every time I write an assert I need to write a unique message or for every step I will have to add a log statement, which is time consuming and will require additional maintenance when updating tests.

Is there an easier way to show this information by including the method call and assert code statements as is?

for example, something like this:

Expected: True
But was: False

On: Assert.That(User.HasOrderInvoice, Is.True)

Steps:
   User.LoginToAccount(UserAccData.TestUserAcc)
   User.AddProductToCart(Data.TestProdData)
   User.PurchaseCart()
   User.GoToOrderHistory()

Solution

  • I was finally able to solve this by using 2 set of libraries:

    1. PostSharp - using AOP I was able to log method calls that represent the steps leading up to assertion
    2. FluentAssertions - Replacing NUnit assertions with FluentAssertions made assertions failures more readable (https://fluentassertions.com/introduction#subject-identification).