age “The Template Class Library was created successfully”. You’ll also find a file named calculatorapp.services.csproj inside the CalculatorApp.Services directory. Next, you need to add this class library project to the calculatorapp solution. To do this, navigate back to the calculatorapp directory, and run the command:
dotnet sln add .\calculatorapp.services\calculatorapp.services.csproj
After successfully running the command, you should get the message “Project added to the solution”.
Inside the CalculatorApp.Services folder, you will find a class Class1 – rename it to Calculator and modify the class as shown in the listing below:
You’ll notice in the above listing that the Add and Sub functions are not implemented. First, we will write a unit test and then implement these functionalities.
Creating the Test project
To add test projects, create a directory called CalculatorApp.Services.Tests and navigate to the directory. In this directory, we will create an MS Test project by running the following command:
dotnet new mstest
This command creates the test project which uses MS Test as the test library. Once the test project is created, add the source project library in the test project. To do that, run the command:
dotnet add reference ../CalculatorApp.Services/CalculatorApp.Services.csproj
This command will add a reference of the CalculatorAppService project into the test project. After adding the reference, add the test project to the solution by navigating to the calculatorapp root directory, and run the command:
dotnet sln add .\CalculatorAppServices.tests\CalculatorAppServices.Tests.csproj
This command will add the test project to the solution. After successfully running the command, you should get the message “Project added to the solution”.
Writing Unit Tests
So far, we’ve created the application source project and a test project. In the application source project, there are unimplemented functions. Now let us write tests for these functions.
In the Test project, I have renamed the file UnitTest1.cs to Calculator.Test.cs and the class name to CalculatorTest. In the constructor of CalculatorTest, we need to create an object of the Calculator class. This can be done as shown in the listing below:
Unit Test for Add function
In the CalculatorTest class, add a unit test method to test the add functionality as shown in the listing below:
To run the test, navigate to the CalculatorApp.Services.Tests directory and execute the command:
You’ll get a ‘test failed’ output because the Add function is not implemented, as shown in the image below:
To pass the test, implement the Add function in the Calculator class as shown in the listing below:
To run the test now, navigate to the CalculatorApp.Services.Tests director and execute the command:
As output, you will get the ‘test passed’ message as shown in the image