Blog

NUnit Testing and Using Moq in C#

NUnit Testing and Using Moq in C#

*To the tune of Willy Wonka singing*
Come with me, and you’ll be, in a world of unit testing informationnnnn.

Unit testing! Unit testing is a great way to ensure that any updates or new functionality added to your code runs smoothly. With well-written tests, you can catch anything that may have been broken by changed methods. 

Getting started can be a little tricky as there are some caveats and neat tricks that are hard to identify at first. In this blog you’ll learn how to get started with NUnit unit testing in C#, use Moq to help enhance these tests, and get testing like a pro. 

Getting Started

To begin, open your project in Visual Studio Enterprise. If the project is opened in a Community or other edition of Visual Studio, you will not be able to view specific breakdowns of the code coverage by section. If you are not concerned with looking at code coverage, this shouldn’t be an issue.

Once the project is opened, select “Test” in the top menu and navigate down to “Test Explorer” to view a layout of all tests.

 Navigating to the Test explorer in Visual Studio Enterprise

This should open the Test Explorer for you, and you will see the following screen:

The test explorer window in Visual Studio enterprise

The Test Explorer

The Test Explorer is where you can view all of the tests built in your project. To run all of the tests at once, select the multi-layered play button in the top left corner. To run individual groups of tests, you can open nested tests and run either groups or individual tests by using the right-hand play button shown in the snapshot below:

 The test explorer window in Visual Studio enterprise

Once you run all of the tests using the play button in the top left corner, you will be able to view the passing or failing status of the test grouping based on the icon next to the grouping. 

In this case, all of our tests have passed and have a green check mark next to them. If a test inside the grouping fails, the grouping will be marked by a red X. 

 The test explorer window in Visual Studio enterprise

You can also use the highlighted icons to filter by passing tests, failing tests, or tests that are not run.

Where Tests Are Located

To locate tests, drill down into the test explorer and double click a test. This will take you to its location in your project

Viewing Code Coverage

To view the code coverage, once you have successfully opened the Test Explorer and run all your tests, return to the “Test” menu and select “Analyze Code Coverage for All Tests.”

Viewing code coverage
 
This will bring up the “Code Coverage Results” window, which you can drill down into to view coverage by sections of the project.

Viewing code coverage

Installing Necessary NuGet Packages

In order to run the tests, you will need to have a few NuGet packages installed in each section of the project with tests present. In this case, tests are present in both Mars.NUnit and in NUnit under Reports, so we will want our packages installed in both sections.

To do this, right click on the portion of the project you would like to install the packages and select “Manage NuGet Packages."

Installing NUget Packages

From here, the packages you will need to install are:

  • Microsoft.CodeCoverage
  • Microsoft.NET.Test.Sdk
  • MSTest.TestAdapter
  • NUnit
  • NUnit3TestAdapter

These packages and their respective versions are also listed in the screenshot below.

Writing your Tests and Using Moq

Writing unit tests is fairly straightforward; the process can be as simple or as complex as you would like. For example, I created a method called AddTwo, which does exactly as the name implies: adds two to my input. 

Writing tests using Moq

I also wrote a test with three test cases: which checks that, when I add two, my answer is what I expected.

Writing tests using Moq
 
As you can see, this is pretty straightforward, and my tests are all passing. Let’s say, however, I had a method called ‘AddThree,’ which depended on a function ‘AddOne’ (the desired result), and ‘AddOne’ had either not been completed, or was still in development. 

This situation is a great example of where we can use Moq to make our lives easier. As shown below, I’ve created my function AddThree():

Writing tests using Moq
I’ve also defined AddOne to be a virtual method. This is so that we can use Moq to mock the method. If your method is private and unable to be scoped to, or virtual, you won’t be able to use Moq to get around this issue. I’ve now written a new test called TestAddThreeMethod and used Moq to mock a call of our AddOne method.

In this case, I’ve updated my AddOne function to erroneously try and add 5 to my function, which would throw off our expected addition of just one:

Writing tests using Moq
Using Moq, we can get around the AddOne method that our AddThree method uses and isolate AddThree, only testing AddThree's functionality.

Writing tests using Moq
 
What I’ve done in the above image is set up a Mock class of my AddingFunctionsClass. In the line below, I’ve instantiated that whenever AddOne gets called inside my mockFunctionClass, it will instead default to using what I have entered in my Returns(), which is my number + 1, the correct output of AddOne. 

You could also hardcode AddOne to return a single value each time, however, this would then no longer show our tests as passing.

Using SetupSequence

SetupSequence is another powerful tool to use in Moq. Let’s say we have a method that gets called multiple times in a function, but we want it to return variable elements for each time it is called. This can be accomplished by using the SetupSequence. For example, we could set our AddOne method to return different results for each time it was called, as shown below:

Using SetupSequence in Moq

If we had called AddOne three times in this scenario, the first time it would return our input plus one, then 3, then 5. 

Another handy feature of Moq is being able to simply skip over methods altogether. Let’s say you have a method that doesn’t return a result but does some Initialization features. You could follow this process, and simply not set a return for the method. This will then simply skip over the method any time it is called. 

 Using SetupSequence in Moq

This statement says any time we call AddOne, don’t return anything, and don’t run AddOne either.

These are some basics and helpful tricks with Moq to get you going. There are a multitude pf more options that can make Moq a powerful tool. With these tools, you’ll be able to write effective and useful tests quickly and make sure that your code runs smoothly and as expected!

NuGet NUnit window

Troubleshooting

It is possible that, when unzipping the project and after building the project, the tests refuse to run. Here are some common tricks that we used to ensure the tests were properly compiling:

  • Attempt a Rebuild of the whole project, and then try running all tests again.
  • Attempt doing a Clean of the whole project and then building. 
  • Try uninstalling the NUnit and NUnit 3 Adapters Nuget packages, and clean the project. Reinstall the packages, rebuild the full project, and then try running all tests again.
  • Some tests may not run after getting errors about other sections in the Report folder. Try building these sections in the Reports folder individually, doing a Build all, then running the tests.

Learn more about DMC's C# programming services and contact us today for your next project!

Comments

There are currently no comments, be the first to post one.

Post a comment

Name (required)

Email (required)

CAPTCHA image
Enter the code shown above:

Related Blog Posts