摘要
本文介绍了Gitlab Runner如何在Windows服务器上调用vstest.console.exe,对旧的项目基于.NET Framework 4.6.1的项目,自动执行单元测试。
改造旧版本的.csproj文件
改造成功后,完整的.csproj文件如下:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ProjectGuid>{4945CE1E-F319-4270-A57C-E9C2A6206CB4}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Yee.Utilities.Tests</RootNamespace>
<AssemblyName>Yee.Utilities.Tests</AssemblyName>
<TargetFramework>net461</TargetFramework>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Yee.Cloud\Yee.Cloud.csproj">
<Project>{2cc2113e-7b17-49c4-a3bc-10f2aba5d837}</Project>
<Name>Yee.Cloud</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.12.0" />
</ItemGroup>
</Project>
重点说明如下:
- TargetFramework
把MSTest换成NUnit
NUnit我们采用3.12.0。
对应的测试适配器也必须采用3.12.0。
- 如果不引用测试适配器,则无法发现测试;
- 如果测试适配器的包引用最新版本,则Visual Studio 2022中能发现测试,但是Gitlab Runner调用vstest.console.exe后无法发现测试。
<ItemGroup>
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.12.0" />
</ItemGroup>
Gitlab服务器上定义环境变量
MSBUILD_PATH、YEE_CLOUD_VERSION_ID和YEE_CLOUD_NUPKG_DIR
在上文中已经解释了这个变量。
其实这里用不掉YEE_CLOUD_NUPKG_DIR
.gitlab-ci.yml
Visual Studio 2022解决方案根目录下放置.gitlab-ci.yml文件,然后签入代码到Gitlab服务器。
.gitlab-ci.yml文件完整如下
stages: # List of stages for jobs, and their order of execution
- build
- test
variables:
YEE_CLOUD_VERSION_ID : 2024.5.$CI_PIPELINE_IID
YEE_CLOUD_NUPKG_DIR : $NUPKG_OUTPUT_ROOT\\Yee.Cloud\\$YEE_CLOUD_VERSION_ID
测试:
stage: test
before_script:
- .$BUILD_LIBRARY_SCRIPT
- .$MSTEST_PS_FILE
script:
- echo "Compiling the code..."
# Yee.Cache.UnitTests
- Build-Project $MSBUILD_PATH $CI_PROJECT_DIR "Yee.Utilities.Tests\\Yee.Utilities.Tests.csproj" $YEE_CLOUD_VERSION_ID
- echo "starting nUnit testing..."
- test-dll $VSTEST_CONSOLE_EXE_DIR $CI_PROJECT_DIR "Yee.Utilities.Tests\\bin\\debug\\net461\\Yee.Utilities.Tests.dll" "x:\\loda\\test"
PowerShell
function test-dll {
param (
[string]$VSTEST_CONSOLE_EXE_DIR,
[string]$ci_project_dir,
[string]$dll_path,
[string]$result_path
)
$dll_file = $ci_project_dir + "\\" + $dll_path
if(( $project_path -like "/*") -or ($project_path -like "\\*")){
$dll_file = $ci_project_dir + $dll_path
}
echo "要测试的库"$dll_file
echo "MSTest所在的路径"$VSTEST_CONSOLE_EXE_DIR
echo "测试报告输出路径"$result_path
cd $VSTEST_CONSOLE_EXE_DIR
.\vstest.console.exe $dll_file
}
执行效果
已知的问题
- PowerShell中如何让Gitlab Runner知道任务出错了?
- 测试报告如何输出?输出后如何让用户看到测试结果?