Testing a console app
Testing a .NET Core console app using NUnit
Creating the source project
Open a shell window. Create a directory called unit-testing-using-nunit to hold the solution. Inside this new directory, run the following command to create a new solution file for the class library and the test project:
Next, create a PrimeService directory. The following outline shows the directory and file structure so far:
Make PrimeService the current directory and run the following command to create the source project:
Rename Class1.cs to PrimeService.cs. You create a failing implementation of the PrimeService
class:
Change the directory back to the unit-testing-using-nunit directory. Run the following command to add the class library project to the solution:
Creating the test project
Next, create the PrimeService.Tests directory. The following outline shows the directory structure:
Make the PrimeService.Tests directory the current directory and create a new project using the following command:
The following outline shows the final solution layout:
Execute the following command in the unit-testing-using-nunit directory:
Creating the first test
You write one failing test, make it pass, and then repeat the process. In the PrimeService.Tests directory, rename the UnitTest1.cs file to PrimeService_IsPrimeShould.cs and replace its entire contents with the following code:
The [TestFixture]
attribute denotes a class that contains unit tests. The [Test]
attribute indicates a method is a test method.
Your test fails. You haven't created the implementation yet. Make the test pass by writing the simplest code in the PrimeService
class that works:
In the unit-testing-using-nunit directory, run dotnet test
again. The dotnet test
command runs a build for the PrimeService
project and then for the PrimeService.Tests
project. After you build both projects, it runs this single test. It passes.
Adding more features
Now that you've made one test pass, it's time to write more. There are a few other simple cases for prime numbers: 0, -1. You could add new tests with the [Test]
attribute, but that quickly becomes tedious. There are other NUnit attributes that enable you to write a suite of similar tests. A [TestCase]
attribute is used to create a suite of tests that execute the same code but have different input arguments. You can use the [TestCase]
attribute to specify values for those inputs.
Instead of creating new tests, apply this attribute to create a single data-driven test. The data driven test is a method that tests several values less than two, which is the lowest prime number:
Run dotnet test
, and two of these tests fail. To make all of the tests pass, change the if
clause at the beginning of the Main
method in the PrimeService.cs file:
Continue to iterate by adding more tests, theories, and code in the main library.
Last updated