Most Complete NUnit Unit Testing Framework Cheat Sheet

Most Complete NUnit Unit Testing Framework Cheat Sheet

An essential part of every UI test framework is the usage of a unit testing framework. One of the most popular ones in the .NET world is NUnit. However, you cannot find a single place where you can get started with its syntax. So, I decided that it would be great to create a complete cheat sheet.  I hope that you will find it useful. Enjoy!

Installation

Install-Package NUnit
Install-Package NUnit.TestAdapter
Install-Package Microsoft.NET.Test.Sdk

Initially, I created the cheat sheet while we developed the first versions of the BELLATRIX automated testing framework. Мost of the stuff in it are still relevant.

Test Execution Workflow

using NUnit.Framework;
namespace NUnitUnitTests
{
    // A class that contains NUnit unit tests. (Required)
    
    public class NonBellatrixTests
    {
        
        public void ClassInit()
        {
            // Executes once for the test class. (Optional)
        }
        
        public void TestInit()
        {
            // Runs before each test. (Optional)
        }
        
        public void TestMethod()
        {
        }
        
        public void TestCleanup()
        {
            // Runs after each test. (Optional)
        }
        
        public void ClassCleanup()
        {
            // Runs once after all tests in this class are executed. (Optional)
            // Not guaranteed that it executes instantly after all tests from the class.
        }
    }
}
// A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly.

public class MySetUpClass
{
    
    public void RunBeforeAnyTests()
    {
        // Executes once before the test run. (Optional)
    }
    
    public void RunAfterAnyTests()
    {
        // Executes once after the test run. (Optional)
    }
}

Attributes Comparison

Comparing NUnit to other frameworks.

NUnit 3.xMSTest v2.xxUnit.net 2.xComments
[Test][TestMethod][Fact]Marks a test method.
[TestFixture][TestClass]n/aMarks a test class.
[SetUp][TestInitialize]ConstructorTriggered before every test case.
[TearDown][TestCleanup]IDisposable.DisposeTriggered after every test case.
[OneTimeSetUp][ClassInitialize]IClassFixture<T>One-time triggered method before test cases start.
[OneTimeTearDown][ClassCleanup]IClassFixture<T>One-time triggered method after test cases end.
[Ignore("reason")][Ignore][Fact(Skip="reason")]Ignores a test case.
[Property][TestProperty][Trait]Sets arbitrary metadata on a test.
[Theory][DataRow][Theory]Configures a data-driven test.
[Category("")][TestCategory("")][Trait("Category", "")]Categorizes the test cases or classes.

Assertions

Assertions- Classic Model

The classic Assert model uses a separate method to express each individual assertion of which it is capable.

Assert.AreEqual(28, _actualFuel); // Tests whether the specified values are equal.
Assert.AreNotEqual(28, _actualFuel); // Tests whether the specified values are unequal. Same as AreEqual for numeric values.
Assert.AreSame(_expectedRocket, _actualRocket); // Tests whether the specified objects both refer to the same object
Assert.AreNotSame(_expectedRocket, _actualRocket); // Tests whether the specified objects refer to different objects
Assert.IsTrue(_isThereEnoughFuel); // Tests whether the specified condition is true
Assert.IsFalse(_isThereEnoughFuel); // Tests whether the specified condition is false
Assert.IsNull(_actualRocket); // Tests whether the specified object is null
Assert.IsNotNull(_actualRocket); // Tests whether the specified object is non-null
Assert.IsInstanceOf(_actualRocket, typeof(Falcon9Rocket)); // Tests whether the specified object is an instance of the expected type
Assert.IsNotInstanceOf(_actualRocket, typeof(Falcon9Rocket)); // Tests whether the specified object is not an instance of type
StringAssert.AreEqualIgnoringCase(_expectedBellatrixTitle, "Bellatrix"); // Tests whether the specified strings are equal ignoring their casing
StringAssert.Contains(_expectedBellatrixTitle, "Bellatrix"); // Tests whether the specified string contains the specified substring
StringAssert.DoesNotContain(_expectedBellatrixTitle, "Bellatrix"); // Tests whether the specified string doesn't contain the specified substring
StringAssert.StartsWith(_expectedBellatrixTitle, "Bellatrix"); // Tests whether the specified string begins with the specified substring
StringAssert.StartsWith(_expectedBellatrixTitle, "Bellatrix"); // Tests whether the specified string begins with the specified substring
StringAssert.IsMatch("(281)388-0388", @"(?d{3})?-? *d{3}-? *-?d{4}"); // Tests whether the specified string matches a regular expression
StringAssert.DoesNotMatch("281)388-0388", @"(?d{3})?-? *d{3}-? *-?d{4}"); // Tests whether the specified string does not match a regular expression
CollectionAssert.AreEqual(_expectedRockets, _actualRockets); // Tests whether the specified collections have the same elements in the same order and quantity.
CollectionAssert.AreNotEqual(_expectedRockets, _actualRockets); // Tests whether the specified collections does not have the same elements or the elements are in a different order and quantity.
CollectionAssert.AreEquivalent(_expectedRockets, _actualRockets); // Tests whether two collections contain the same elements.
CollectionAssert.AreNotEquivalent(_expectedRockets, _actualRockets); // Tests whether two collections contain different elements.
CollectionAssert.AllItemsAreInstancesOfType(_expectedRockets, _actualRockets); // Tests whether all elements in the specified collection are instances of the expected type
CollectionAssert.AllItemsAreNotNull(_expectedRockets); // Tests whether all items in the specified collection are non-null
CollectionAssert.AllItemsAreUnique(_expectedRockets); // Tests whether all items in the specified collection are unique
CollectionAssert.Contains(_actualRockets, falcon9); // Tests whether the specified collection contains the specified element
CollectionAssert.DoesNotContain(_actualRockets, falcon9); // Tests whether the specified collection does not contain the specified element
CollectionAssert.IsSubsetOf(_expectedRockets, _actualRockets); // Tests whether one collection is a subset of another collection
CollectionAssert.IsNotSubsetOf(_expectedRockets, _actualRockets); // Tests whether one collection is not a subset of another collection
Assert.Throws<ArgumentNullException>(() => new Regex(null)); // Tests whether the code specified by delegate throws exact given exception of type T

Assertions- Constraint Model

The constraint-based Assert model uses a single method of the Assert class for all assertions. The logic necessary to carry out each assertion is embedded in the constraint object passed as the second parameter to that method. The second argument in this assertion uses one of NUnit’s syntax helpers to create an EqualConstraint

Assert.That(28, Is.EqualTo(_actualFuel)); // Tests whether the specified values are equal.
Assert.That(28, Is.Not.EqualTo(_actualFuel)); // Tests whether the specified values are unequal. Same as AreEqual for numeric values.
Assert.That(_expectedRocket, Is.SameAs(_actualRocket)); // Tests whether the specified objects both refer to the same object
Assert.That(_expectedRocket, Is.Not.SameAs(_actualRocket)); // Tests whether the specified objects refer to different objects
Assert.That(_isThereEnoughFuel, Is.True); // Tests whether the specified condition is true
Assert.That(_isThereEnoughFuel, Is.False); // Tests whether the specified condition is false
Assert.That(_actualRocket, Is.Null); // Tests whether the specified object is null
Assert.That(_actualRocket, Is.Not.Null); // Tests whether the specified object is non-null
Assert.That(_actualRocket, Is.InstanceOf<Falcon9Rocket>()); // Tests whether the specified object is an instance of the expected type
Assert.That(_actualRocket, Is.Not.InstanceOf<Falcon9Rocket>()); // Tests whether the specified object is not an instance of type
Assert.That(_actualFuel, Is.GreaterThan(20)); // Tests whether the specified object greater than the specified value
Assert.That(28, Is.EqualTo(_actualFuel).Within(0.50));
// Tests whether the specified values are nearly equal within the specified tolerance.
Assert.That(28, Is.EqualTo(_actualFuel).Within(2).Percent);
// Tests whether the specified values are nearly equal within the specified % tolerance.
Assert.That(_actualRocketParts, Has.Exactly(10).Items);
// Tests whether the specified collection has exactly the stated number of items in it.
Assert.That(_actualRocketParts, Is.Unique);
// Tests whether the items in the specified collections are unique.
Assert.That(_actualRocketParts, Does.Contain(_expectedRocketPart));
// Tests whether a given items is present in the specified list of items.
Assert.That(_actualRocketParts, Has.Exactly(1).Matches<RocketPart>(part => part.Name == "Door" && part.Height == "200"));
// Tests whether the specified collection has exactly the stated item in it.

Advanced Attributes

Author Attribute

The Author Attribute adds information about the author of the tests. It can be applied to test fixtures and to tests.


[Author("Joro Doev", "joro.doev@bellatrix.solutions")]
public class RocketFuelTests
{
    
    public void RocketFuelMeassuredCorrectly_When_Landing() { /* ... */ }
    
    [Author("Ivan Penchev")]
    public void RocketFuelMeassuredCorrectly_When_Flying() { /* ... */ }
}

Repeat Attribute

RepeatAttribute is used on a test method to specify that it should be executed multiple times. If any repetition fails, the remaining ones are not run and a failure is reported.


[Repeat(10)]
public void RocketFuelMeassuredCorrectly_When_Flying()
{ /* ... */ }

Combinatorial Attribute

The CombinatorialAttribute is used on a test to specify that NUnit should generate test cases for all possible combinations of the individual data items provided for the parameters of a test.

[Test, Combinatorial]
public void CorrectFuelMeassured_When_X_Site([Values(1, 2, 3)] int x, [Values("A", "B")] string s)
{
    ...
}

Generated tests:

Pairwise Attribute

The PairwiseAttribute is used on a test to specify that NUnit should generate test cases in such a way that all possible pairs of values are used.

[Test, Pairwise]
public void ValidateLandingSiteOfRover_When_GoingToMars
([Values("a", "b", "c")] string a, [Values("+", "-")] string b, [Values("x", "y")] string c)
{
    Debug.WriteLine("{0} {1} {2}", a, b, c);
}

Resulted pairs:

a + y

a - x 

b - y

b + x

c - x

c + y

Random Attribute

The RandomAttribute is used to specify a set of random values to be provided for an individual numeric parameter of a parameterized test method.

The following test will be executed fifteen times, three times for each value of x, each combined with 5 random doubles from -1.0 to +1.0.


public void GenerateRandomLandingSiteOnMoon([Values(1, 2, 3)] int x, [Random(-1.0, 1.0, 5)] double d)
{
    ...
}

Range Attribute

The RangeAttribute is used to specify a range of values to be provided for an individual parameter of a parameterized test method. NUnit creates test cases from all possible combinations of the provided on parameters - the combinatorial approach.


public void CalculateJupiterBaseLandingPoint([Values(1, 2, 3)] int x, [Range(0.2, 0.6)] double y)
{
    //...
}

Generated tests:

Retry Attribute

RetryAttribute is used on a test method to specify that it should be rerun if it fails, up to a maximum number of times.


[Retry(3)]
public void CalculateJupiterBaseLandingPoint([Values(1, 2, 3)] int x, [Range(0.2, 0.6)] double y)
{
    //...
}

Timeout Attribute

The TimeoutAttribute is used to specify a timeout value in milliseconds for a test case. If the test case runs longer than the time specified it is immediately cancelled and reported as a failure, with a message indicating that the timeout was exceeded.

[Test, Timeout(2000)]
public void FireRocketToProximaCentauri()
{
    ...
}

Execute Tests in Parallel

Parallel execution of methods within a class is supported starting with NUnit 3.7. In earlier releases, parallel execution only applies down to the TestFixture level, ParallelScope.Childrenworks as ParallelScope.Fixtures and any ParallelizableAttribute placed on a method is ignored.

[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: LevelOfParallelism(3)]

The ParallelizableAttribute may be specified on multiple levels of the tests. Settings at a higher level may affect lower level tests, unless those lower-level tests override the inherited settings.


[Parallelizable(ParallelScope.Fixtures)]
public class TestFalcon9EngineLevels
{
    // ...
}

Related Articles

Resources, Web Automation

Most Exhaustive WebDriver Locators Cheat Sheet

As you know, I am keen on every kind of automation especially related to web technologies. So, I enjoy using Selenium WebDriver. You can find lots of materials

Most Exhaustive WebDriver Locators Cheat Sheet

Mobile Automation, Resources

Most Complete Appium C# Cheat Sheet

The next article from the mobile test automation series will be dedicated to Appium. All you need to to know – from the most basic operations to the most advanc

Most Complete Appium C# Cheat Sheet

Resources, Web Automation Java

Most Complete Selenium WebDriver Kotlin Cheat Sheet

As you know, I am a big fan of Selenium WebDriver. You can find tones of useful Kotlin/Java code in my Web Automation Java Series. I lead automated testing cour

Most Complete Selenium WebDriver Kotlin Cheat Sheet

Resources, Web Automation Java

Most Complete Selenium WebDriver Java Cheat Sheet

As you know, I am a big fan of Selenium WebDriver. You can find tonnes of useful Java code in my Web Automation Java Series. I lead automated testing courses an

Most Complete Selenium WebDriver Java Cheat Sheet

Development

Assert DateTime the Right Way MSTest NUnit C# Code

NUnit has added built-in support for this using the keyword Within.

Assert DateTime the Right Way MSTest NUnit C# Code

Development

Specification-based Test Design Techniques for Enhancing Unit Tests

The primary goal of most developers is usually achieving 100% code coverage if they write any unit tests at all. In this test design how-to article, I am going

Specification-based Test Design Techniques for Enhancing Unit Tests
Anton Angelov

About the author

Anton Angelov is Managing Director, Co-Founder, and Chief Test Automation Architect at Automate The Planet — a boutique consulting firm specializing in AI-augmented test automation strategy, implementation, and enablement. He is the creator of BELLATRIX, a cross-platform framework for web, mobile, desktop, and API testing, and the author of 8 bestselling books on test automation. A speaker at 60+ international conferences and researcher in AI-driven testing and LLM-based automation, he has been recognized as QA of the Decade and Webit Changemaker 2025.