简体   繁体   English

c#:自动测试中的 DllImport 问题

[英]c#: Problem with DllImport on automated testing

i have a method registered like this:我有一个这样注册的方法:

    [DllImport("MyApi.dll", CharSet = CharSet.Ansi)]
    private static extern int SomeRandomCall();

and i added the MyApi.dll to the project with "Copy always = true" and locally everything compiles fine and the MSTest Unittests are working...我将 MyApi.dll 添加到项目中,并使用“始终复制 = true”,并且在本地一切编译正常,MSTest 单元测试正在工作......

But: When i try to run the unittests manually via console, like:但是:当我尝试通过控制台手动运行单元测试时,例如:

mstest.exe /testcontainer:C:\mytestdll.dll

the tests are failing and that's because mstest ( which finally executes the tests in my dll ) expects the MyApi.dll to be in its directory ( C:\Windows[...]\IDE 7\MSTest.exe )... Ok, makes sense, but:测试失败,这是因为 mstest (最终在我的 dll 中执行测试)期望 MyApi.dll 位于其目录中( Z0D61F8370CAD1D412F80B84D143E1257 ,有道理,但是:

As C# attributes require constant values as parameters, i can not use sth.由于 C# 属性需要常量值作为参数,我不能使用 sth。 like "GetCurDir() + "MyApi.dll"... What is the best solution to handle this "dynamic path to MyApi.dll" problem?像“GetCurDir() +”MyApi.dll”......处理这个“MyApi.dll 的动态路径”问题的最佳解决方案是什么?

The only thing i can think of right now is conditional compiler symbols, but that's pretty dirty...我现在唯一能想到的是条件编译器符号,但这很脏......

The DllImport is fine as it is; DllImport很好; what you need to do is make sure the library loader can find MyApi.dll at runtime.您需要做的是确保库加载器可以在运行时找到 MyApi.dll。 One way to accomplish this is with the PATH environment variable:实现此目的的一种方法是使用 PATH 环境变量:

set PATH=%PATH%;C:\

mstest.exe /testcontainer:C:\mytestdll.dll

...assuming MyApi.dll is in C:\ (not recommended). ...假设 MyApi.dll 位于C:\ (不推荐)。

Judging from http://bytes.com/topic/c-sharp/answers/440208-dllimport-attribute-where-default-dll-location , you may want to try preloading the library before calling the [DllImport] decorated method with LoadLibrary.http://bytes.com/topic/c-sharp/answers/440208-dllimport-attribute-where-default-dll-location来看,您可能想在调用 [DllImport] 修饰方法之前尝试预加载库 LoadLibrary . Hopefully DLL is found if its already loaded, no matter where its loaded from.如果 DLL 已经加载,则希望找到它,无论它是从哪里加载的。 You'll need to call LoadLibrary via pinvoke.您需要通过 pinvoke 调用 LoadLibrary。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM