Chr*_*ris 4 c# unit-testing mstest vstest.console.exe microsoft-data-sqlclient
在我的代码中使用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 测试运行器中正常工作 - 那么问题是什么?
问题在于VSTest.Console.exe扫描单元测试程序集的依赖项并将结果复制到输出目录以进行测试。
尽管Microsoft.Data.SqlClient包依赖包Microsoft.Data.SqlClient.SNI正确地将Microsoft.Data.SqlClient.SNI.x86.dll和Microsoft.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()
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将确保 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
Run Code Online (Sandbox Code Playgroud)