Skip to content
Go back

Test Automation- Multiple Asserts Using NUnit Testing Framework

Published:

Introduction

In this article, I will review a relatively new feature in NUnit 3 - C# testing framework. This feature is called “Multiple Asserts”.

The tools used to demonstrate the following examples are:

Why should we want to use multiple assertions?

  1. Less testing code.
  2. Multiple asserts are much faster.
  3. Before this feature, We had to write two test cases that assert a different section or to write the assertions one after the other. In case there are multiple asserts and one failsthe assert after the failed assert will not run, opposite to the feature that verifies all!

The before state:

[Test, Description("Checks for URL title")]
public void TestTitle() {
    Assert.That(driver.Title, Is.EqualTo("Not Google"));
}

[Test, Description("Checks for URL")]
public void TestURL() {
    Assert.That(driver.Url, Is.EqualTo("http://www.google.com/"));
}

Using the multiple assertions, here is the after outcome:

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace NUnit.Tests1 {
    [TestFixture]
    public class TestClass {
        IWebDriver driver;

        [SetUp]
        public void BeforeTestMethod() {
            driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://www.google.com/");
        }

        [Test, Description("Checks for title and URL")]
        public void TestTitleURL() {
            Assert.Multiple(() => {
                Assert.That(driver.Title, Is.EqualTo("Not Google"));
                Assert.That(driver.Url, Is.EqualTo("http://www.google.com/"));
            });
        }

        [TearDown]
        public void AfterTestMethod() {
            driver.Quit();
        }
    }
}

When the test fails - all the failed assertions are aggregated into a single place:

Test Name:   TestMethod
Test Outcome:  Failed
Test Duration:  0:00:10.604

Result1 Name:   TestTitleURL

Result1 Outcome:  Failed
Result1 Duration:  0:00:05.302
Result1 Message:
Expected string length 10 but was 6. Strings differ at index 0.
  Expected: "Not Google"
  But was:  "Google"
  ----------^

Result2 Name:   TestTitleURL

Result2 Outcome:  Failed
Result2 Duration:  0:00:05.302

Expected string length 22 but was 34. Strings differ at index 4.
  Expected: "http://www.google.com/"
  But was:  "https://www.google.com/?gws_rd=ssl"
  ----------------^

In conclusion

In this article, we reviewed the NUnit 3 multiple assertions feature and it’s advantages. Further reading on the multiple assertions in this link.

Happy testing!


Suggest Changes

Have a challenge? Let's Talk


Previous Post
Test Automation - Review On Selenium WebDriver JavaScript CLI
Next Post
Test Automation - How To Dockerize Our API Testing