C# 8.0 and. NET Core 3.0 advanced programming sharing Note 6: Part III unit test

Fixing bug s in your code is expensive. The earlier errors are found in the development process, the lower the repair cost.

Unit testing is a good way to find bugs early in development. Some developers even follow the principle that programmers should create unit tests before writing code, which becomes text driven development (TDD).

Microsoft provides a special unit testing framework called MSTest; However, the third-party unit testing framework xUnit.net will be used here.

4.4.1 create class libraries to be tested

Perform the following steps:

(1) Create two subfolders named CalculatorLib and CalculatorLibUnitTests in the Chapter04 folder and add them to the workspace respectively. (I created a new Calculator folder due to an operation error) like other steps, add and create 2 subfolders, and then right-click to add them to the workspace.

(2) Navigate to Terminal|new Terminal and select CalculatorLib.

(3) Enter the following command in the terminal window:

dotnet new classlib

(4) Rename the file named Class1.cs to Calculator.cs.

(5) Modify the Calculator.cs file to define it as the Calculator class (write addition as multiplication with a deliberate error). If you think the code is messy, use Ctrl+A to select all under Visual Studio Code, and then use Ctrl+K and Ctrl+F to automatically format the code layout, as shown below:

namespace CalculatorLib;
public class Calculator
{
    public double Add(double a, double b)
    {
        return a * b;
    }
}

(6) Enter the following command in the terminal window:

dotnet build

(7) Navigate to Terminal|New Terminal and select calculatorlibunit tests.

(8) Enter the following command in the terminal window:

dotnet new xunit

(9) Click the file named CalculatorLibUnitTests.csproj, modify the configuration to add the ItemGroup section, and the others contain references to CalculatorLib items, as shown below:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="coverlet.collector" Version="3.0.2">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CalculatorLib\CalculatorLib.csproj"/>

</ItemGroup>
</Project>

(10) Rename the file UnitTest1.cs to CalculatorUnitTests.cs

(11) Enter the following command in the terminal window:

dotnet build

4.4.2 writing unit tests

A good unit test consists of the following three parts.

  • Array: this section declares and instantiates variables for input and output.
  • Act: this section executes the unit you want to test. In our example, this means calling the method to be tested.
  • Assert: this section asserts the output. Assertion is a belief. If it is not true, it means that the test fails. For example, when calculating 2 + 2, the expected result is 4.

Now let's write unit tests for the Calculator class.

(1) Open CalculatorUnitTests.cs, rename the class CalculatorUnitTests, import the CalculatorLib namespace, and then modify the CalculatorUnitTests class to have two test methods, calculating 2 plus 2 and 2 plus 3 respectively, as shown below:

using Xunit;
using System;
using CalculatorLib;
namespace CalculatorLibUnitTests;

public class CalculatorUnitTests
{
    [Fact]
    public void TestAdding2And2()
    {
        //arrange
        double a=2;
        double b=2;
        double expected=4;
        var calc=new Calculator();
        //act
    double actual=    calc.Add(a,b);
    Assert.Equal(expected,actual); 
    }

    [Fact]
    public void TestAdding2And3()
    {
    //arrange
    double a=2;
    double b=3;
    double expected=5;
    var calc=new Calculator();
    //act
    double actual=calc.Add(a,b);

    //assert
    Assert.Equal(expected,actual);
     
    }
}

4.4.3 operation unit test

(1) Enter the following command in the terminal window of the calculatorlibunit test project:

dotnet test

(2) Note that the output surface runs two tests: one passes and the other fails.

(3) The multiplication in the method of correcting A is addition.

(4) Run the unit test again and you will find that the BUG has been repaired and the test has passed.

PS D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests> dotnet test
  Determining items to restore
  All items are up to date and cannot be restored.
     at CalculatorLibUnitTests.CalculatorUnitTests.TestAdding2And3() in D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests\CalculatorUnitTests.cs:line 33
 fail!  - fail:     1,adopt:     1,Skipped:     0,total:     2,Duration: 2 ms - CalculatorLibUnitTests.dll (net6.0)
PS D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests>PS D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests>PS D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests> dotnet test
  Determining items to restore... All items are up-to-date and cannot be restored.
  You are using .NET Preview of. Please check https://aka.ms/dotnet-core-preview  CalculatorLib -> D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLib\bin\Debug\net6.0\CalculatorLib.dll
  CalculatorLibUnitTests -> D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests\bin\Debug\net6.0\CalculatorLibUnitTests.dllD:\LearningRecords\doc\C#\Test run of NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests\bin\Debug\net6.0\CalculatorLibUnitTests.dll (.NETCoreApp,Version=v6.0)
Microsoft (R) Test execution command line tool version 17.0.0-preview-20210817-02
 copyright (C) Microsoft Corporation. All rights reserved.
Please wait while test execution starts...
A total of 1 test file matches the specified pattern.
Passed! - fail:     0,adopt:     2,Skipped:     0,total:     2,Duration: 2 ms - CalculatorLibUnitTests.dll (net6.0)PS D:\LearningRecords\doc\C#\NetCoreWorkspace\Code\Calculator\CalculatorLibUnitTests>

Posted by Sayian on Sat, 06 Nov 2021 10:24:32 -0700