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

运行XUnit对接SQL Server测试时提示SqlServerDataAttribute数据发现器不存在

问题原因与修复步骤
    1. 测试方法缺少[Theory]属性
      xunit 所有数据驱动测试都必须搭配[Theory]特性使用,仅添加[SqlServerData]无法被识别为合法的理论测试,修改测试方法代码如下:
[Theory] // 新增这一行
[SqlServerData("ServerIp", "DbName", "DbUser","DbPwd", "SELECT name FROM Users")]
public void Test1(string name)
{
    Assert.Equal("T C One", name);
}
    1. DataDiscoverer特性参数需要写全限定名
      你当前在DataAdapterDataAttribute上标注的[DataDiscoverer("DataAdapterDataAttributeDiscoverer", "Tests")]第一个参数仅写了类名,xunit 加载时可能无法正确匹配类型,需要修改为包含命名空间的完整名称:
[DataDiscoverer("Tests.DataAdapterDataAttributeDiscoverer", "Tests")] // 补全命名空间
public abstract class DataAdapterDataAttribute : DataAttribute
    1. 确认OleDbDataAttribute的实现
      你贴出的代码中SqlServerDataAttribute继承自OleDbDataAttribute,需要保证OleDbDataAttribute是DataAdapterDataAttribute的子类,并且正确实现了抽象属性DataAdapter,示例实现参考:
using System.Data.OleDb;
using System.Data;

namespace Tests
{
    public abstract class OleDbDataAttribute : DataAdapterDataAttribute
    {
        private readonly string _connectionString;
        private readonly string _selectStatement;

        protected OleDbDataAttribute(string connectionString, string selectStatement)
        {
            _connectionString = connectionString;
            _selectStatement = selectStatement;
        }

        protected override IDataAdapter DataAdapter 
            => new OleDbDataAdapter(_selectStatement, _connectionString);
    }
}
    1. 安装必要的NuGet包
      .NET Core/.NET 5+ 运行时默认不包含OleDb相关组件,需要手动安装System.Data.OleDb NuGet包,否则运行时会抛出找不到提供程序的错误。
    1. 可选配置:如果需要在测试发现阶段就加载数据,可以在SqlServerData特性上设置EnableDiscoveryEnumeration = true,默认关闭状态下只有测试运行时才会查询数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:48:03