Getting Started with NUnit 3

I couldn’t find any good tutorials on how to get NUnit 3 set up, so I put this one together!

Once Per Computer

  1. Install NUnit3 Test Adapter

    In VS2015, Tools > Extensions and Updates, click Online, search for NUnit3, Download and Install NUnit 3 Test Adapter. Click Restart Now to finish installation of the Test Adapter.

For Each Solution

  1. Make sure that the classes you want to test in your main project are public

  2. Add a Class Library project to the solution

    Right-click on the solution in Solution Explorer, choose Add > New Project. Choose the type Class Library and call it YourProjectName.Test.

  3. Add NUnit to the test project using NuGet

    Right-click on the .Test project in Solution Explorer, choose Manage NuGet Packages. Search for NUnit, and select NUnit (version 3.something). Click the Install button.

  4. Add a reference to the main project in your Test project

    Right-click on the .Test project in Solution Explorer, choose Add > Reference. Click on Projects on the left pane, then put a check mark next to your main project and click OK.

  5. Set up your first test class

    Rename Class1.cs in your test project to something more descriptive, like SequentialSearchTest.cs if you plan to test SequentialSearch. When asked if you would like to rename all references of Class1, choose Yes. Put the line using NUnit.Framework at the top of the file.

  6. Use the Test attributes to define your class and the test methods.

    Put [TestFixture] just before the class declaration. You can use [Test] before a normal test method and [TestCase(...)] before methods that will take multiple sets of parameters. An example test is below:

    using NUnit.Framework;
    
    namespace BasicAlgorithms.Test
    {
        [TestFixture]
        public class SequentialSearchTest
        {
            int[] testArray = { 7, 5, 3, 2, 9, 11, 19, 0, 60, 4 };
    
            [Test]
            public void shouldFindAllElementsInTestArray()
            {
                foreach (var x in testArray)
                {
                    Assert.That(Program.Contains(testArray, x), Is.True);
                }
            }
    
        }
    }
    

  7. Build the solution to have the Test Explorer automatically discover tests

    First show the Test Explorer window by going to Test > Windows > Test Explorer. Then build your solution, and your test method(s) should automatically be found. If they aren’t found, make sure they have the [Test] attributes.

  8. Click Run All to have the tests run. If there are errors, they will show up as failing tests. Tests that ran successfully show up as passing tests.

Check out the NUnit documentation for more information!

Leave a Reply