【问题标题】:Unable to load DLL 'Microsoft.Data.SqlClient.SNI.x86.dll' from Unit Tests when using Microsoft.Data.SqlClient 2.0使用 Microsoft.Data.SqlClient 2.0 时无法从单元测试加载 DLL 'Microsoft.Data.SqlClient.SNI.x86.dll'
【发布时间】:2020-10-14 09:05:55
【问题描述】:

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

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 测试运行程序中也可以正常工作 - 那么问题是什么?

【问题讨论】:

    标签: c# unit-testing mstest vstest.console.exe microsoft-data-sqlclient


    【解决方案1】:

    问题是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多