问题描述
在我的代码中使用 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测试运行程序中也可以正常工作-那么问题是什么?
解决方法
问题是 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()
{
}
}
}
这将确保存在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