Tuesday, October 11, 2011

Introduction to NUnit Assertions

Continuing our tutorial after the first NUnit program, lets get ourselves bit accustomed with the central command/class in the framework - "Assert"

The Assert class defines tons of static methods which we use to verify the correctness of the program under test. So our test cases essentially perform some action on the program and then assert whether the outcome is what we expect. For eg: passing two arguments 2 & 3 to an Add method should return 5. If the method returns anything other than 5 then the Assertion fails which in turn marks the test-case as failed. Simple right! Yes!

So lets write few simple test-cases to see the Assert in action.To keep things simple lets not bother ourselves to find a program to test, we will simply use assertions on variables.
So go ahead and add a new class to the solution (Right click on solution name > Add > Class) and name it SimpleAssertions.cs. Paste the below code in this class file, rebuild the solution and Run the test-cases in NUnit

using System;
using NUnit.Framework;

namespace NUnitTest1
{
    [TestFixture]
    class SimpleAssertions
    {
        [Test]
        public void Add()
        {
            int val = 5 + 5;
            Assert.AreEqual(10, val);
        }

        [Test]
        public void FindGreater()
        {
            int a = 45;
            int b = 28;
            Assert.Greater(a, b);
        }

        [Test]
        public void CheckNull()
        {
            string str = "";
            Assert.NotNull(str);
        }

        [Test]
        public void IgnoreCase()
        {
            string small = "something";
            string caps = "SOMETHING";
            StringAssert.AreEqualIgnoringCase(small, caps);
        }
    }
}

Nothing fancy going here and the code is extremely readable thanks to clear method-names in NUnit. All the test-cases will pass when you run them.



No comments:

Post a Comment