{"id":748,"date":"2017-11-21T16:10:00","date_gmt":"2017-11-21T16:10:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=748"},"modified":"2025-02-21T07:18:33","modified_gmt":"2025-02-21T07:18:33","slug":"unit-tests-net-core-app","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/unit-tests-net-core-app","title":{"rendered":"How To Write Unit Tests for a .NET Core Application"},"content":{"rendered":"\n<p>In the TDD approach, before implementing a functionality, you write a unit test for it. For example, if you want to write a function to add two numbers, first you\u2019ll write a failed unit test and then implement the functionality to pass the test.<\/p>\n\n\n\n<p>In this post, we\u2019ll create a Calculator Application. To start, let\u2019s follow the folder structure as outlined below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>CalculatorApp \u2013 Solution<\/li>\n\n\n\n<li>CalculatorApp.Services \u2013 Application project<\/li>\n\n\n\n<li>CalculatorApp.Services.Tests \u2013 Test project<\/li>\n<\/ul>\n\n\n\n<p>You can use Visual Studio to create projects; however, in this post, I will use .NET Core commands to create my projects, add tests, and run tests. You can also use MSTest or NUnit to write unit tests, but in this example, I\u2019ll use xUnit and dotnet test to write and run my Unit Tests.<\/p>\n\n\n\n<p>Let\u2019s start by opening a command shell and follow along:&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"creating-the-application-project\">Creating the Application Project<\/h2>\n\n\n\n<p>To start, you\u2019ll need to create a directory called <b>CalculatorApp<\/b>. Keep in mind that you can follow any naming convention you\u2019d like for directories, but if you\u2019d like to follow along with this post, I would recommend following the same directory name. So, let\u2019s create the CalculatorApp directory and navigate to it.<\/p>\n\n\n\n<p>Inside the CalculatorApp directory, we are going to create a new solution by running the following command:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet new sln<\/h3>\n\n\n\n<p>After successfully running the command, you should get the message \u201cThe Template Solution File was created successfully\u201d.&nbsp; Also inside the CalculatorApp directory, you will find a file named calculatorapp.sln.<\/p>\n\n\n\n<p>Next, create a directory called <b>CalculatorApp.Services. <\/b>This directory will keep the application sources i.e. all classes of the calculator application. Navigate to the Calculatorapp.Services directory and create a class library by running the following command:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet new classlib<\/h3>\n\n\n\n<p>After successfully running this command, you should get the message \u201cThe Template Class Library was created successfully\u201d. You\u2019ll 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:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet sln add .\\calculatorapp.services\\calculatorapp.services.csproj<\/h3>\n\n\n\n<p>After successfully running the command, you should get the message \u201cProject added to the solution\u201d.<\/p>\n\n\n\n<p>Inside the CalculatorApp.Services folder, you will find a class <b>Class1<\/b> &#8211; rename it to <b>Calculator<\/b> and modify the class as shown in the listing below:&nbsp;<\/p>\n\n\n\n<p><b><span style=\"text-decoration: underline;\">Calculator.cs<\/span><\/b><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using System;\nnamespace calculatorapp.services {\n    public class Calculator {\n        public int Add(int num1, int num2) {\n            throw new NotImplementedException();\n        }\n        public int Sub(int num1, int num2) {\n            throw new NotImplementedException();\n        }\n    }\n}<\/pre>\n\n\n\n<p>You\u2019ll 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. &nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating the Test Project<\/h3>\n\n\n\n<p>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:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet new mstest<\/h3>\n\n\n\n<p>This command creates the test project which uses MS Test as the test library. &nbsp;Once the test project is created, add the source project library in the test project. To do that, run the command:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">dotnet add reference ..\/CalculatorApp.Services\/CalculatorApp.Services.csproj<\/h4>\n\n\n\n<p><b>&nbsp;<\/b>This<b> <\/b>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&nbsp; run the command:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet sln add .\\CalculatorAppServices.tests\\CalculatorAppServices.Tests.csproj<\/h3>\n\n\n\n<p>This command will add the test project to the solution. After successfully running the command, you should get the message \u201cProject added to the solution\u201d.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"writing-unit-tests\">Writing Unit Tests<\/h2>\n\n\n\n<p>So far, we\u2019ve 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.<\/p>\n\n\n\n<p>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:&nbsp;<\/p>\n\n\n\n<p><b><span style=\"text-decoration: underline;\">Calculator.Test.cs<\/span><\/b><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Microsoft.VisualStudio.TestTools.UnitTesting;\nusing calculatorapp.services;\nnamespace CalculatorApp.Services.Tests {\n    [TestClass]\n    public class CalculatorTest {\n        Calculator _calc;\n        public CalculatorTest() {\n            _calc = new Calculator();\n        }\n    }\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test For Add Function<\/h3>\n\n\n\n<p>In the CalculatorTest class, add a unit test method to test the add functionality as shown in the listing below:&nbsp;<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[TestMethod]\npublic void shouldaddtwonumbers() {\n    int res = _calc.Add(5, 3);\n    Assert.AreEqual(res, 8);\n}<\/pre>\n\n\n\n<p>To run the test, navigate to the CalculatorApp.Services.Tests directory and execute the command:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet test&nbsp; <\/h3>\n\n\n\n<p>You\u2019ll get a \u2018test failed\u2019 output because the Add function is not implemented, as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"776\" height=\"347\" src=\"https:\/\/staging.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image.png\" alt=\"\" class=\"wp-image-1663\" srcset=\"https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image.png 776w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-300x134.png 300w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-768x343.png 768w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-480x215.png 480w\" sizes=\"auto, (max-width: 776px) 100vw, 776px\" \/><\/figure>\n\n\n\n<p>To pass the test, implement the Add function in the Calculator class as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public int Add(int num1, int num2) {\n    int result = num1 + num2;\n    return result;\n}<\/pre>\n\n\n\n<p>To run the test now, navigate to the CalculatorApp.Services.Tests director and execute the command:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet test&nbsp; <\/h3>\n\n\n\n<p>As output, you will get the \u2018test passed\u2019 message as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"697\" height=\"265\" src=\"https:\/\/staging.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-1.png\" alt=\"\" class=\"wp-image-1664\" srcset=\"https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-1.png 697w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-1-300x114.png 300w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-1-480x182.png 480w\" sizes=\"auto, (max-width: 697px) 100vw, 697px\" \/><\/figure>\n\n\n\n<p>Now you have implemented the Add functionality while adhering to the TDD approach in a .NET Core application!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test For Sub Function<\/h3>\n\n\n\n<p>In the CalculatorTest class, add a unit test method to test the sub functionality as shown in the listing below:&nbsp;<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[TestMethod]\npublic void shouldsubstracttwonumbers() {\n    int res = _calc.Sub(5, 3);\n    Assert.AreEqual(res, 2);\n}<\/pre>\n\n\n\n<p>To run the test, navigate to the CalculatorApp.Services.Tests directory and execute the command:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet test&nbsp; <\/h3>\n\n\n\n<p>Here, your test will fail because the Sub function is not implemented. You will get one failed test result as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"814\" height=\"405\" src=\"https:\/\/staging.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-2.png\" alt=\"\" class=\"wp-image-1665\" srcset=\"https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-2.png 814w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-2-300x149.png 300w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-2-768x382.png 768w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-2-480x239.png 480w\" sizes=\"auto, (max-width: 814px) 100vw, 814px\" \/><\/figure>\n\n\n\n<p>To pass the test, implement the Sub function in the Calculator class as shown in the below listing:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public int Sub(int num1, int num2) {\n    int result = num1 - num2;\n    return result;\n}<\/pre>\n\n\n\n<p>Now run the test again by navigating to the CalculatorApp.Services.Tests directory and executing:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">dotnet test<\/h3>\n\n\n\n<p>Now you\u2019ll find both tests passed, as seen here:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"743\" height=\"278\" src=\"https:\/\/staging.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-3.png\" alt=\"\" class=\"wp-image-1666\" srcset=\"https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-3.png 743w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-3-300x112.png 300w, https:\/\/www.infragistics.com\/blogs\/wp-content\/uploads\/2017\/11\/image-3-480x180.png 480w\" sizes=\"auto, (max-width: 743px) 100vw, 743px\" \/><\/figure>\n\n\n\n<p>Now you have implemented Sub functionality while adhering to the TDD approach in a .NET Core application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"wrapping-up\">Wrapping Up<\/h2>\n\n\n\n<p>So far in this post, we\u2019ve created a .NET Core Calculator application while adhering to the TDD approach. To create tests, we used the XUnit and dotnet tests. For your reference, here is the source code of both the Calculator class and its test class:<\/p>\n\n\n\n<p><b><span style=\"text-decoration: underline;\">Calculator.cs<\/span><\/b><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using System;\nnamespace calculatorapp.services {\n    public class Calculator {\n        public int Add(int num1, int num2) {\n            int result = num1 + num2;\n            return result;\n        }\n        public int Sub(int num1, int num2) {\n            int result = num1 - num2;\n            return result;\n        }\n    }\n}<\/pre>\n\n\n\n<p><b><span style=\"text-decoration: underline;\">Calculator.test.cs<\/span><\/b><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Microsoft.VisualStudio.TestTools.UnitTesting;\nusing calculatorapp.services;\nnamespace CalculatorApp.Services.Tests {\n    [TestClass]\n    public class CalculatorTest {\n        Calculator _calc;\n        public CalculatorTest() {\n                _calc = new Calculator();\n            }\n            [TestMethod]\n        public void shouldaddtwonumbers() {\n                int res = _calc.Add(5, 3);\n                Assert.AreEqual(res, 8);\n            }\n            [TestMethod]\n        public void shouldsubstracttwonumbers() {\n            int res = _calc.Sub(5, 3);\n            Assert.AreEqual(res, 2);\n        }\n    }\n}<\/pre>\n\n\n\n<p>And that\u2019s how you write unit tests and then implement their functionalities. I hope this post helps you in getting started with writing unit tests for your next .NET Core application!<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"\/products\/ignite-ui\"><img decoding=\"async\" src=\"https:\/\/download.infragistics.com\/marketing\/Blog-in-content-ads\/Ignite-UI-JavaScript\/Blog-incontent-IgniteUI-650x200.jpg\" alt=\" \"\/><\/a><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Writing unit tests is a good software engineering practice. In this article, we will learn how to create a C# .NET Core application while adhering to the Test Driven Development (TDD) approach. <\/p>\n","protected":false},"author":65,"featured_media":1667,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-748","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-how-to"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/748","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=748"}],"version-history":[{"count":4,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/748\/revisions"}],"predecessor-version":[{"id":2121,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/748\/revisions\/2121"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/1667"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=748"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=748"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=748"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}