You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xunit中定义融合Fact与Trait的自定义特性?

实现自定义的[FactIntegration]特性

你可以通过继承Xunit的FactAttribute并实现ITraitAttribute接口来创建兼具两种功能的自定义特性,具体代码如下:

using Xunit;
using Xunit.Abstractions;

public class FactIntegrationAttribute : FactAttribute, ITraitAttribute
{
    public IEnumerable<KeyValuePair<string, string>> Traits => 
        new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("integration", "whatever")
        };
}

定义完成后,直接在测试方法上标记[FactIntegration],就等价于同时使用[Fact]和[Trait("integration", "whatever")]:

[FactIntegration]
public void MyIntegrationTest()
{
    // 测试逻辑
}

原理很直白:

  • 继承FactAttribute让自定义特性拥有标记测试方法的能力,和原生[Fact]功能完全一致;
  • 实现ITraitAttribute接口并返回指定键值对,就能自动为测试添加对应的分类特性,替代手动写[Trait]的操作。

内容的提问来源于stack exchange,提问作者Darren Oakey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:02:32