Creating Tests with NUnit

Course Home | Code Example(s)

So as mentioned in the first NUnit lesson, NUnit provides us with the framework to mark code as tests, provides assertion capabilities and a mechanism for running tests. Now aside from assertions, the tests themselves contain little else from NUnit. The majority of the code will be calls to other classes and libraries to help us interact with our application/codebase.

So let’s assume we’ve written some code that we want to turn into a test. The bare minimum we can do it simply add [Test] above the method name.

using System;
using NUnit.Framework;

namespace CSharpBasics.nunitlessons
{
    public class A_CreatingATest
    {
        //In order to use NUNit we need to add the package to our Project
        //So as covered in Lesson 2 of C# Basics we can do that using NuGet

        //Then we have two option, we can just write 'using NUnit.Framework;' at the top of our class
        //Or if you just type [Test] and place the cursor after the t and press Cmd/Ctrl + K 
        //VS will recommend packages for you to use, the top on should be NUnit and it will add it to the class
        [Test]
        public void MultipleNumbers()
        {
            int c = 5 * 6;
            Console.WriteLine(c);
        }
    }
}

This block of code will now be recognised as a test by the test runner. We look at running them in a few lessons time.

Next Lesson ➔

Resources

NUnit - Writing Tests

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