2

在我的代码中使用Microsoft.Data.SqlClient包(2.0 版)时,当通过 CI 提供程序中的VSTest.console.exe执行单元测试时(以及在本地运行时),我收到以下错误:

System.TypeInitializationException:“Microsoft.Data.SqlClient.TdsParser”的类型初始化程序引发异常。---> System.TypeInitializationException:“Microsoft.Data.SqlClient.SNILoadHandle”的类型初始化程序引发了异常。---> System.DllNotFoundException:无法加载 DLL 'Microsoft.Data.SqlClient.SNI.x86.dll':找不到指定的模块

代码正确执行,单元测试在 NCrunch 和 Visual Studio 2019 测试运行程序中也可以正常工作 - 那么问题是什么?

4

1 回答 1

2

问题是VSTest.Console.exe扫描单元测试程序集的依赖项并将结果复制到输出目录进行测试。

虽然Microsoft.Data.SqlClient包依赖包Microsoft.Data.SqlClient.SNI正确地将Microsoft.Data.SqlClient.SNI.x86.dllMicrosoft.Data.SqlClient.SNI.x64.dll文件放置在程序集输出文件夹中,VSTest.Console.exe不会自动将它们识别为依赖项并将它们复制到测试输出文件夹,因此测试失败。

我的解决方法是通过专用测试类明确指定 DLL 作为测试的部署项,如下所示:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyTests
{
    /// <summary>
    /// Ensures Microsoft.Data.SqlClient dependencies exist for tests.
    /// </summary>
    /// <remarks>
    /// This class performs no tests and is here purely to ensure that the Microsoft.Data.SqlClient.SNI.*
    /// exist for unit testing purposes (specifically when VSTest.Console is used by the build).
    /// This was introduced for Microsoft.Data.SqlClient 2.0.1 and Microsoft.Data.SqlClient.SNI 2.1.0.
    /// Thos packages need to be a package reference on the unit test project.
    /// Later versions may not need this workaround.
    /// </remarks>
    [TestClass]
    [DeploymentItem("Microsoft.Data.SqlClient.SNI.x86.dll")]
    [DeploymentItem("Microsoft.Data.SqlClient.SNI.x64.dll")]
    public class TestSqlClient
    {
        [TestMethod]
        public void TestSqlClient_Test()
        {
        }
    }
}

这将确保 DLL 存在以进行测试。不理想但有效!

此外,如果它有用,这就是我运行VSTest.Console.exe来诊断此问题的方式:

VSTest.Console /Diag:D:\Temp\trace.log /ResultsDirectory:D:\Temp\TestResults d:\Repos\YourRepo\YourProject.Tests\bin\Debug\YourProject.Tests.dll
于 2020-10-14T09:05:55.517 回答