【问题标题】:How to let xUnit runner only execute tests in specific classes?如何让 xUnit runner 只在特定类中执行测试?
【发布时间】:2025-12-24 08:45:17
【问题描述】:

在我的 csproj 文件中,我定义了一个测试目标,用于在指定的 DLL 中执行 xunit 测试:

<UsingTask AssemblyFile="..\packages\xunit.1.9.2\lib\net20\xunit.runner.msbuild.dll"     TaskName="Xunit.Runner.MSBuild.xunit" />
  <Target Name="Test">
    <xunit Assembly="bin\Debug\My.Project.dll" />
</Target>

这很好用,但是我希望能够指定只执行某些类中的测试。这可能吗?

【问题讨论】:

    标签: msbuild xunit xunit.net


    【解决方案1】:

    您可以将xunit 任务切换为Exec 任务并运行XUnit 控制台运行程序xunit.console.clr4.exe。这具有用于指定要运行的“特征”的命令行选项。这些是可以使用 TraitAttribute 分配给测试的名称值对:

        [Trait("TraitName", "TraitValue")]
        public void MyTest(){ /*..*/ }
    

    来自控制台运行器的使用测试:

    Valid /trait "name=value" : only run tests with matching name/value traits : if specified more than once, acts as an OR operation /-trait "name=value" : do not run tests with matching name/value traits : if specified more than once, acts as an AND operation

    【讨论】:

    • 您还可以使用带有完整方法名称的 -method 参数,例如:xunit.console.clr4.exe -method Namespace.ClassName.MethodName
    • @aguafrommars,随着 V2 的发布,它变得更加容易:xunit.console.exe -class 'Namespace.ClassName'