What are Assertions?

Course Home | Code Example(s)

So we’ve written some code that exercises our application. We’ve marked it as a test, but how do we know if our test was successful? This is where assertions come in.

Assertions are important. Very important when it comes to automated checking. This is our attempt at replacing ourselves. When we run the scenario we are automating, how are we deciding if what the application is presenting us is acceptable? We need to work out what this is and instruct our code to do the assertions that meet that acceptable criterion. Fortunately, they give us many options for doing this.

using System;
using NUnit.Framework;

namespace CSharpBasics.nunitlessons
{
    public class C_Assertions
    {
        [Test]
        public void TestOne()
            {
                int c = 5 * 5;

                //So our first assertion is using the Assert class from NUnit.
                //The first parameter is the ExpectedResult, the second parameter is the actual value.
                //So here I'm expecting our calculation above to be 25.
                Assert.AreEqual(25, c);

                //We can also add a contextual message. NUnit will display this message upon failure
                //Creating good contextual messages can really speed up debugging
                Assert.AreEqual(25, c, "contextual message on failure here");
                //We can use assertEquals for strings, ints, objects

                //NUnit then also gives us many other options

                //Assert.IsFalse(); Checking something is false
                //Assert.AreNotEqual (); Doesn't matter what the value is along as its not this value
                //Assert.NotNull() Isn't null
                //Assert.AreNotSame() Same as NotEquals
                //Assert.AreSame(); Same as equals above
                //Assert.IsTrue(); Checking something is true
            }
    }
}

Important note to add here, designing good assertions is a skill, a skill that doesn’t require coding knowledge. So if you are struggling to design acceptable assertions, involve the team and seek help. As always stated, these assertions are very important.

So now, you’ve spent time reading and exploring the asserts above, you’ll be very happy to know that I don’t want you to use them! Someone would class the above methods as legacy. I’d agree. But it’s important for you to understand them, you may see them in existing test suites, but it’s also so you can take the same journey as others. Check out the next lesson to learn about matchers.

Next Lesson ➔

Resources

NUnit Assertions Documentation

Richard Bradshaw's photo
Author

Richard Bradshaw

@FriendlyTester

Software Tester, speaker and trainer at Friendly Testing. BossBoss at Ministry of Testing. Whiteboard Testing creator. Striving to improve the testing craft.

Comments