{"id":378,"date":"2019-11-01T19:58:00","date_gmt":"2019-11-01T19:58:00","guid":{"rendered":"http:\/\/paradysz.pl\/?p=378"},"modified":"2019-12-02T23:15:46","modified_gmt":"2019-12-02T23:15:46","slug":"unit-testing-in-net-for-the-beginners","status":"publish","type":"post","link":"https:\/\/paradysz.pl\/index.php\/2019\/11\/01\/unit-testing-in-net-for-the-beginners\/","title":{"rendered":"Unit testing in .NET for the beginners"},"content":{"rendered":"\n<p class=\"justify-text\">I&#8217;m actually preparing a presentation about unit testing in .NET in order to convince one of a team to start implementing it. For some of us, this is an obvious thing that our code should be covered by unit tests but still, there are a big number of projects without them. So, all who don&#8217;t enough feel a sense of unit test creation, I encourage you to finish reading this post.<\/p>\n\n\n\n<h2>What is unit testing?<\/h2>\n\n\n\n<p class=\"justify-text\">In simple language &#8211; level of software testing where individual components of a software are tested. What does it mean? Let me show a plain example.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class BankAccount\n{\n        private readonly string m_customerName;\n        private double m_balance;\n\n        public BankAccount(string customerName, double balance)\n        {\n            m_customerName = customerName;\n            m_balance = balance;\n        }\n\n        public double Balance\n        {\n            get { return m_balance; }\n        }\n\n        public void Debit(double amount)\n        {\n            if (amount &gt; m_balance)\n            {\n                throw new ArgumentOutOfRangeException(&quot;amount&quot;);\n            }\n\n            if (amount &lt; 0)\n            {\n                throw new ArgumentOutOfRangeException(&quot;amount&quot;);\n            }\n\n            m_balance -= amount;\n        }\n}\n<\/pre><\/div>\n\n\n<p class=\"justify-text\">The above piece of code implements a basic bank account class with a method to withdraw money called <em>void Debit(double amount)<\/em>. It checks if the payout amount is less then account balance and if the payout amount is greater then zero. If so, we are able to withdraw this amount. Now, we want to verify if our method works properly, hence, let&#8217;s create a first unit test.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;TestMethod]\npublic void Debit_WithValidAmount_UpdatesBalance()\n{\n    \/\/ Arrange\n    double beginningBalance = 11.99;\n    double debitAmount = 4.55;\n    double expected = 7.44;\n    BankAccount account = new BankAccount(&quot;Mr. Bryan Walton&quot;, beginningBalance);\n\n    \/\/ Act\n    account.Debit(debitAmount);\n\n    \/\/ Assert\n    double actual = account.Balance;\n    Assert.AreEqual(expected, actual, 0.001, &quot;Account not debited correctly&quot;);\n}\n<\/pre><\/div>\n\n\n<p class=\"justify-text\">The test checking if the method, for beginning balance = 11,99 and debit amount = 4,55, decreases account balance by 7,44 what is a correct assumption: 11,99 &#8211; 4,55 = 7,44. There is only one unit test for this method but of course, we can add others to verify what happens when the debt amount is greater than the account balance or when the debt is less than zero. Try to do it yourself!<\/p>\n\n\n\n<h2>Why do we need to unit tests?<\/h2>\n\n\n\n<ul class=\"justify-text\"><li><strong>Quality of code<\/strong><br>Unit tests check cases that you could skip in your implementation. Moreover, attachment of unit tests execution in your CI build or verification of test coverage keep your code in good health.<\/li><li><strong>Finds bugs early<\/strong><br>It detects issues that may have come up before code is sent further to the repository or merge to master. <\/li><li><strong>Simplify the debugging process<\/strong><br>Run existing unit tests before start implementing a new feature. If a test fails afterward, it means that only the latest changes made in the&nbsp;code need to be debugged. <\/li><li><strong>TDD<\/strong><br>Writing tests before actual coding (TDD) makes you think harder about the problem, hence, your code would be more bugs-free then it is. <\/li><\/ul>\n\n\n\n<h2>Popular Unit testing frameworks for .NET<\/h2>\n\n\n\n<p class=\"justify-text\">According to RedMonk 2018 report, a framework that gets the most questions on StackOverflow is NUnit, however, XUnit is getting be popular too. Furthermore, keep in mind that at the beginning of .NET life most developers used to implement unit tests using MSTest, so you can also meet unit tests implemented in this framework. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" width=\"498\" height=\"364\" src=\"http:\/\/paradysz.pl\/wp-content\/uploads\/2019\/11\/image.png\" alt=\"\" class=\"wp-image-410\" srcset=\"https:\/\/paradysz.pl\/wp-content\/uploads\/2019\/11\/image.png 498w, https:\/\/paradysz.pl\/wp-content\/uploads\/2019\/11\/image-300x219.png 300w\" sizes=\"(max-width: 498px) 100vw, 498px\" \/><\/figure><\/div>\n\n\n\n<h2>Mocking<\/h2>\n\n\n\n<p class=\"justify-text\">Mocking is creating objects that simulate the behavior of real objects. Once again, let me show me a short example to explain what exactly I mean.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class CreditDecision\n{\n   private readonly ICreditDecisionService _creditDecisionService;\n   public CreditDecision(ICreditDecisionService creditDecisionService)\n   {\n      _creditDecisionService = creditDecisionService;\n   }\n\n   public string MakeCreditDecision(int creditScore)\n   {\n      if (creditScore &lt; 0)\n      {\n         throw new ArgumentException(&quot;Credit score can not be negative number.&quot;, nameof(creditScore));\n      }\n\n   return _creditDecisionService.GetCreditDecision(creditScore);\n   }\n}\n\npublic interface ICreditDecisionService\n{\n     string GetCreditDecision(int creditScore);\n}\n<\/pre><\/div>\n\n\n<p class=\"justify-text\">Above, we have a class responsible for a credit decision containing a method <em>public string MakeCreditDecision(int creditScore)<\/em> which produces a credit decision in text format. It may be noted the method calls another <em>GetCreditDecision <\/em>method from the <em>ICreditDecisionService<\/em> interface. This interface has been injected across a constructor. <\/p>\n\n\n\n<p class=\"justify-text\">Now, we would like to create the unit tests for the <em>MakeCreditDecision<\/em> method but we need to know what exactly the <em>GetCreditDecision <\/em>method from <em>ICreditDecisionService <\/em>does. If it updates some tables from DB or invokes some events we will execute undesirable actions. In order to avoid these actions we just need to add the mocking mechanism. It thanks to mocks we can simulate the behavior of the methods, properties, etc. How to create mock objects using Moq which is the most popular mocking framework in .NET? Look at an example below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Test]\npublic void CreditDecision_MakeCreditDecision_CreditScoreGreaterThenZero_ReturnsCreditDecision()\n{\n   \/\/ Arrange\n   mockCreditDecisionService = new Mock&lt;ICreditDecisionService&gt;(MockBehavior.Strict);\n   mockCreditDecisionService.Setup(p =&gt;p.GetCreditDecision(It.IsAny&lt;int&gt;())).Returns(&quot;Credit Decision&quot;);\n   var systemUnderTest = new CreditDecision(mockCreditDecisionService.Object);\n   var expectResult = &quot;Credit Decision&quot;;\n\n   \/\/ Act\n   var result = systemUnderTest.MakeCreditDecision(543);\n\n   \/\/ Assert\n   Assert.That(result, Is.EqualTo(expectResult));\n}\n<\/pre><\/div>\n\n\n<p class=\"justify-text\">As we can see the <em>GetCreditDecision<\/em> method has been mocked. It means for each integer parameter it returns just simple text: &#8220;Credit Decision&#8221; what it is fully enough for our tests because we don&#8217;t want to verify the behavior for the <em>GetCreditDecision<\/em> method. The aim of the test is checking if the method returns a proper credit decision in a string format for a credit score greater then zero. Additionally, another case that is worth to check is the case for a credit score of less than zero. In this case, we should get <em>ArgumentException<\/em> and mock object is not required then.<\/p>\n\n\n\n<h2>When doing unit tests does not make sense <\/h2>\n\n\n\n<ul class=\"justify-text\"><li>Do not create test cases for everything. Instead, focus on the tests that impact the behavior of the system. <\/li><li>The code is trivial e.g setters and getters. <\/li><li>If the test itself is an order of magnitude more difficult to write than the code. <\/li><li>If the tests run is very expensive like complex calculation or call external resources which causing extra cost.<\/li><li>Do not test external libraries.<\/li><\/ul>\n\n\n\n<h2>Summary<\/h2>\n\n\n\n<p class=\"justify-text\">On the end, I would like to leave you with a quote from the book &#8220;Software Testing Techniques&#8221; written by Boris Beizer to draw some conclusions.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p> <em>More than the act of testing, the act of designing tests is one of the best bug preventers known. The thinking that must be done to create a useful test can discover and eliminate bugs before they are coded \u2013 indeed, test-design thinking can discover and eliminate bugs at every stage in the creation of software, from conception to specification, to design, coding and the rest.<\/em> <\/p><\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m actually preparing a presentation about unit testing in .NET in order to convince one of a team to start implementing it. For some of us, this is an obvious thing that our code should be covered by unit tests but still, there are a big number of projects without them. So, all who don&#8217;t [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":380,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/posts\/378"}],"collection":[{"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/comments?post=378"}],"version-history":[{"count":40,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/posts\/378\/revisions"}],"predecessor-version":[{"id":449,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/posts\/378\/revisions\/449"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/media\/380"}],"wp:attachment":[{"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/media?parent=378"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/categories?post=378"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/paradysz.pl\/index.php\/wp-json\/wp\/v2\/tags?post=378"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}