Adding .NET Unit Tests
Instructions for creating unit tests using the .NET 5.0 and .NET core 3.1 stacks.
.NET unit tests are run with the
dotnet test
command. Here are a few things to keep in mind when creating .NET unit tests:First add
<GenerateProgramFile>false</GenerateProgramFile>
inside the <PropertyGroup></PropertyGroup>
tags in the *.csproj file. This will prevent the "Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point." error from occurring when the test runs.If you're using the xUnit testing framework and .NET 5.0, add the following to the *.csproj file:
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<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="1.3.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
For xUnit and .NET core 3.1, add the following to *.csproj:
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.2.0" />
</ItemGroup>
If you're using NUnit (for .NET 5.0 or .NET core 3.1), add the following to you *.csproj file:
<ItemGroup>
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0"/>
</ItemGroup>
The project directory must be specified for .NET unit tests if the project files are in a folder rather than the ~/workspace directory.
The
dotnet test
command can take around 30 seconds to run. Since tasks timeout after 60 seconds, linking multiple .NET unit tests to a single task may cause the task to timeout. Linking a single unit test to each task helps ensure the task can complete successfully and report the results to the user.Last modified 2yr ago