Getting Started With Unit Testing Using C# And xUnit

Unit Testing is a software testing approach which is performed at development time to test the smallest component of any software. It means rather than testing the big module in one go, you test the small part of that module. A small component in the sense that it could be any function, any property or any class which is handling the specific functionality.

Unit test cases help us to test and figure out whether the individual unit is performing the task in a good manner or not. It basically ensures us that the system is designed as per the requirements and help us to figure out the bugs before putting the actual code to the QA environment.

More articles on ASP.NET Core which you may like.

  1. First Application in Asp.Net Core MVC 2.0
  2. 10 New Features of Asp.Net Core 2.0
  3. Publish Asp.Net Core 2.0 Application on IIS
  4. Getting started with Razor Pages in Asp.Net Core 2.0
  5. ASP.NET Core Web API with Oracle Database and Dapper

When we talk about Unit Testing in Software Development, we have lots of advantages if we write it along with the actual code as follows.

  1. Unit Test cases reveal if anything is wrong with software design, software functionality and if it is not working as expected as per the requirements.
  2. Due to the help of the Unit Testing, we can get or catch the bugs or issues early before deploying the code to another environment and fixing it.
  3. Mostly, we will follow the TDD approach while implementing the Unit Testing. And this Unit Testing helps us to understand the requirements and think about complexity if we will write the actual code for software development. So, Unit Testing gives us an idea or gives us time to think about actual requirements implementation at the time of writing the test cases.
  4. Adding the Unit Testing is the part of your software development cycle that makes the process more Agile. If anything changes with code or older code due to some bug or issue which is written by some other developers, then Unit Test cases show if your code is breaking the functionality or not.
  5. Unit Testing helps us to reduce the number bugs early. If a developer has understood the requirements clearly and based on that if he writes the code for implementing the requirements along with Test Cases, then probably he can catch and fix most of the bugs at the time of development.
  6. Unit Testing helps other developers also to understand the actual functionality, about the unit components that are available in the system and how they work.

As we can see above, writing the Unit Testing helps us to understand the software design, how we will implement it in a better way, catching the bugs or errors early and fixing them and many more.

But there are some disadvantages as well.

  1. It increases the duration for completing the project because writing the Unit Testing along with actual requirements implementation take some extra time.
  2. It increases the cost of the project, as we know that the billing in the software industry is based on time duration; if time increases the cost will also increase. As we all know, writing the Unit Testing takes much more time by the developers, so it increases the time duration of the project which basically increases the cost of the project.
  3. We can write the Unit Test case where requirements are not clear or changing too quickly, either we should wait to freeze the requirements or write and change the test cases every time if requirements get changed.
  4. Code coverage is not 100% because, in any scenario, we can not write the Unit Test Cases for the functionality. For instance, if you have an algorithm which changes based on data.
  5. Writing the Unit Test Cases and maintaining it is a headache.
  6. Unit Testing cannot catch all types of bugs. There are lots of bugs left behind in the system after Unit Testing which can be found in Integration Testing or End to End testing.

Tips to write a Test Case.

  1. Don’t write Unit Test Cases in the same project, create a separate test project for Unit Testing.
  2. Unit Test Cases should be well organized and maintainable.
  3. Write Unit Test Cases only for small functionality.
  4. If a function is performing so many operations then just write Unit Test Case for each individual function,
  5. Don’t write Unit Test Cases which are dependent on another Unit Test Cas.
  6. The name of the function for Unit Test Case should be self-explanatory.
  7. Unit Test Cases should always be independent.
  8. Performance wise, Unit Test Case should always be fast.

PRACTICAL EXAMPLE

Let’s understand it with a practical demonstration. For that, first, we will create an ASP.NET Core Console Application using Visual Studio 2017 with the name of UnitTestingDemo. Once the project is ready just add a new class as “MathOperation.cs” which is responsible for performing some of the math operations as follows.

MathOperation.cs

namespace UnitTestingDemo  
{  
    public static class MathOperation  
    {          
        public static double Add(double number1, double number2)  
        {             
            return (number1 + number2);  
        }  
  
        public static double Subtract(double number1, double number2)  
        {  
            return (number1 - number2);  
        }  
  
        public static double Multiply(double number1, double number2)  
        {  
            return (number1 * number2);  
        }  
  
        public static double Divide(double number1, double number2)  
        {  
            return (number1 / number2);  
        }  
    }  
}

As we can see with the above code in MathOperation class, we have four methods as Add, Subtract, Multiply and Divide and each method takes two input parameters and returns the output.

Now, we will create one more project for Unit Testing. So, just right click on the solution “UnitTestingDemo” and choose “Add” and then “New Project”. From the .NET Core section, we have to choose “xUnit Test Project (.NET Core)” and provide the suitable name for this project as “XUnitTestDemo” and click OK.

xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework. Written by the original inventor of NUnit v2, xUnit.net is the latest technology for unit testing C#, F#, VB.NET, and other .NET languages. Know more about xUnit Here.

We have a project ready now for Unit Testing, let get the reference of the main project within the testing project so that we can access the MathOperation class’s methods while writing test cases.

To add the reference, just right click on Dependencies of the testing project and click on “Add Reference..”. It will open a “Reference Manager” dialog from where we can get the reference of other projects, dll and many more. So, just click on Solution inside the Projects from the left panel and select the main project and click on OK.

Unit Testing Using C# And xUnit

Now, create one class in “XUnitTestDemo” project named “MathOperationTest.cs” where we will write the unit test case for MathOperation.cs class’s methods. Here, we will create four different test methods to test four different methods. And each method will be gone through with three processes -- one arranges the data for testing, the second performs the operation with required values and the last checks if the expected value is equal to the actual value or not. Following is the MathOperationTest class where we have implemented test cases.  

using UnitTestingDemo;  
using Xunit;  
  
namespace XUnitTestDemo  
{  
    public class MathOperationTest  
    {  
        [Fact]  
        public void Task_Add_TwoNumber()  
        {  
            // Arrange  
            var num1 = 2.9;  
            var num2 = 3.1;  
            var expectedValue = 6;  
  
            // Act  
            var sum = MathOperation.Add(num1, num2);  
  
            //Assert  
            Assert.Equal(expectedValue, sum, 1);  
        }  
  
        [Fact]  
        public void Task_Subtract_TwoNumber()  
        {  
            // Arrange  
            var num1 = 2.9;  
            var num2 = 3.1;  
            var expectedValue = -0.2;  
  
            // Act  
            var sub = MathOperation.Subtract(num1, num2);  
  
            //Assert  
            Assert.Equal(expectedValue, sub, 1);  
        }  
  
        [Fact]  
        public void Task_Multiply_TwoNumber()  
        {  
            // Arrange  
            var num1 = 2.9;  
            var num2 = 3.1;  
            var expectedValue = 8.99;  
  
            // Act  
            var mult = MathOperation.Multiply(num1, num2);  
  
            //Assert  
            Assert.Equal(expectedValue, mult, 2);  
        }  
  
        [Fact]  
        public void Task_Divide_TwoNumber()  
        {  
            // Arrange  
            var num1 = 2.9;  
            var num2 = 3.1;  
            var expectedValue = 0.94; //Rounded value  
  
            // Act  
            var div = MathOperation.Divide(num1, num2);  
  
            //Assert  
            Assert.Equal(expectedValue, div, 2);  
        }  
    }  
}

Now, let's run all test cases and see the status. To run the test cases, just move to Test Explorer in Visual Studio where you will find all the Unit Test Cases list. To run it, just click to Run All and it will start executing the test case. Test Case execution time decision is based on how complex your test case is. Once it will run successfully, the output will be as follows.

Unit Testing Using C# And xUnit

Conclusion

So, today we have learned what Unit Testing is and what are the advantages and disadvantages of Unit Testing and how to implement Unit Testing with ASp.NET Core Console Application using xUnit Framework.

I hope this post will help you. Please leave your feedback in the comments which helps me to improve myself for the next post. If you have any doubts please ask them,  and If you like this post, please share it with your friends. Thanks.


Similar Articles