1 4_testing_your_code
Jason Zhu edited this page 2021-02-23 13:57:37 +11:00

Module 4. Testing Your Code

Reference:

The Many Benefits of Unit Test

Benefits:

  • Verify: Positive test
  • Investigate: (Important) Negative test help to check whether code can handle error, misusage from users. And investiage whether it's wrong
  • Small Units of Code
  • Test Runner: tool in framework used to run automatically and generate test report

We use xUnit.net in this module

Creating a Unit Test Project

Convention steps of creating xunit UT in .NET:

  1. mkdir -p /test/GradeBooks.test; By convention, Unit Test is a individual project separated from main src. it's normally named as "project+.test"
  2. cd into /GradeBooks.test and dotnet new xunit

How to get xunit:

  • xunit is 3rd party package. Need use nuget to get it.
  • dotnet add package xunit --version 2.4.1 following nuget xunit .NET CLI
  • Adding pacakge will store reference in .csproj file, which good for dotnet restore

Writing and Running a Test

using System;
using Xunit;

namespace GradeBook.Tests
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            ...
        }
    }
}

Introduction to xUnit structure:

  1. using Xunit bring "Xunit" namespace into program.
    1. In the namesapce, there will API and datatypes to be used with xUnit
  2. Test case is within class
  3. [Fact] is C# attribute (decoration). xUnit when load UTs will look for [Fact] attributes for testing

Running test runner:

  • From cli: dotnet test in UT directory with .test.csproj
  • From VScode:

General structure of test codes:

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        // arrange (data prepare)

        // act

        // assert (Assertion to verify)
    }
}

Referenceing Projects and Packages

Rename

  1. Rename class to reference projects
  2. Rename filename to match class name
  3. Create test case with correct instance initialization

Steps for referencing projects & packages in a csproj:

  1. Add package into test project using dotnet add package <e.g. xunit>
  2. Add reference of other src project into test proj using dotnet add reference [PATH] following dotnet add reference
  3. Add public access modifier to Book, so it can be exposed for reference
  4. Adding namespace to make sure both src code share same namespace
  <ItemGroup>
    <ProjectReference Include="..\..\src\GradeBook\GradeBook.csproj" />
  </ItemGroup>

Refactoring for Tesetability

If a single method doing too many things, need break it up. DON'T WRITE LARGE METHODS.