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:
mkdir -p /test/GradeBooks.test
; By convention, Unit Test is a individual project separated from main src. it's normally named as "project+.test"- cd into
/GradeBooks.test
anddotnet 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 fordotnet restore
Writing and Running a Test
using System;
using Xunit;
namespace GradeBook.Tests
{
public class UnitTest1
{
[Fact]
public void Test1()
{
...
}
}
}
Introduction to xUnit structure:
using Xunit
bring "Xunit" namespace into program.- In the namesapce, there will API and datatypes to be used with xUnit
- Test case is within class
[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
- Rename class to reference projects
- Rename filename to match class name
- Create test case with correct instance initialization
Steps for referencing projects & packages in a csproj:
- Add package into test project using
dotnet add package <e.g. xunit>
- Add reference of other src project into test proj using
dotnet add reference [PATH]
following dotnet add reference - Add
public
access modifier toBook
, so it can be exposed for reference - 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.