当 AnyCPU 测试程序集实现 x64 生产程序集的接口时出现 BadImageFormatException

发布于 2025-01-03 15:20:17 字数 3491 浏览 3 评论 0原文

我似乎遇到了这样一个场景:当我在引用 x64 程序集的 AnyCPU 程序集上运行 mstest 时,我收到 BadImageFormatException。

当 AnyCPUTestingx64Production.dll 测试程序集实现 x64Production.dll 中的接口(即使未使用)时,会出现此问题:

Unable to load the test container 'D:\AnyCPUTestingx64Production.dll' 
or one of its dependencies. error details:
System.BadImageFormatException: 
    Could not load file or assembly 'x64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
  • mstest 在 Windows 7 64 位上运行,
  • 测试程序集构建为 AnyCPU,以使其在 64 位计算机上运行64 位主机(如所述 此处)
  • testsettings 文件指定
  • peverify 和 corflags 没有显示任何有趣的内容,
  • 这很容易在玩具解决方案中重现,即
    • x64 制作
      • 未引用其他程序集
      • 仅包含一个空的公共接口 IExampleInterface
      • 设置为 x64
    • 任何 CPU 测试 x64 生产
      • 仅引用 x64Production.dll(即,即使没有引用 Microsoft.VisualStudio.QualityTools.UnitTestFramework,也会出现此问题)
      • 仅包含 x64Production.IExampleInterface 的空实现
      • 设置为 x64
  • nunit 可以加载并运行测试程序集(一旦我转换了所有测试属性)
    • 但这并不是解决更大问题(涉及大量项目文件)的良好短期解决方案
  • 无论项目的目标是 3.5 还是 4.0,
  • 都会出现同样的问题。无论使用 VS2008 还是 VS2010 c# 编译器,都会出现同样的问题
  • 无论使用 VS2010 还是测试代理中的 mstest,都会出现同样的问题,
  • 加载 AnyCPUTestingx64Production 时 mstest 会失败 - 即这不是尝试的问题在错误的 QTAgent 中加载程序集(进程监视器中没有显示任何内容,并且重命名 QTAgent32.exe 没有效果):
    *** Assembly Binder Log Entry  (09/02/2012 @ 09:44:26) ***

    The operation failed.
    Bind result: hr = 0x8007000b. An attempt was made to load a program with an incorrect format.

    Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
    Running under executable  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe
    --- A detailed error log follows. 

    === Pre-bind state information ===
    LOG: User = David
    LOG: DisplayName = x64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
     (Fully-specified)
    LOG: Appbase = file:///D:/
    LOG: Initial PrivatePath = NULL
    LOG: Dynamic Base = NULL
    LOG: Cache Base = NULL
    LOG: AppName = MSTest.exe
    Calling assembly : AnyCPUTestingx64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
    ===
    LOG: This bind starts in default load context.
    LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe.Config
    LOG: Using host configuration file: 
    LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
    LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
    LOG: Attempting download of new URL file:///D:/x64Production.DLL.
    LOG: Assembly download was successful. Attempting setup of file: D:\x64Production.dll
    LOG: Entering run-from-source setup phase.
    LOG: Assembly Name is: x64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
    ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

是否有其他人确定这在 VS2010 mstest 中是否不受支持?

I seem to have hit on a scenario where when I run mstest on an AnyCPU assembly which references an x64 assembly, I get a BadImageFormatException.

The issue occurs when an interface in x64Production.dll is implemented (even if unused) by the AnyCPUTestingx64Production.dll test assembly:

Unable to load the test container 'D:\AnyCPUTestingx64Production.dll' 
or one of its dependencies. error details:
System.BadImageFormatException: 
    Could not load file or assembly 'x64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
  • mstest is running on windows 7 64-bit
  • the test assembly is built as AnyCPU to get it to run in 64bit on a 64bit host (as outlined here)
  • the testsettings file specifies <Execution hostProcessPlatform="MSIL"/>
  • peverify and corflags reveal nothing interesting
  • this is readily reproducible in a toy solution, i.e. where
    • x64Production
      • references no other assemblies
      • includes only an empty public interface IExampleInterface
      • has <PlatformTarget> set to x64
    • AnyCPUTestingx64Production
      • references only x64Production.dll (i.e. this issue is present even without a reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework)
      • includes only an empty implementation of x64Production.IExampleInterface
      • has <PlatformTarget> set to x64
  • nunit can load and run the test assembly (once I've converted all the test attributes)
    • but is not a good short term solution to the larger problem (which involves a huge number of project files)
  • the same issue arises whether the projects target 3.5 or 4.0
  • the same issues arises whether the VS2008 or VS2010 c# compiler is used
  • the same issue arises whether mstest from VS2010 or Test Agents is used
  • it is mstest which fails while loading AnyCPUTestingx64Production - i.e this is not an issue with attempting to load the assembly in the wrong QTAgent (nothing shows up in Process Monitor and renaming QTAgent32.exe has no effect):
    *** Assembly Binder Log Entry  (09/02/2012 @ 09:44:26) ***

    The operation failed.
    Bind result: hr = 0x8007000b. An attempt was made to load a program with an incorrect format.

    Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
    Running under executable  C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe
    --- A detailed error log follows. 

    === Pre-bind state information ===
    LOG: User = David
    LOG: DisplayName = x64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
     (Fully-specified)
    LOG: Appbase = file:///D:/
    LOG: Initial PrivatePath = NULL
    LOG: Dynamic Base = NULL
    LOG: Cache Base = NULL
    LOG: AppName = MSTest.exe
    Calling assembly : AnyCPUTestingx64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
    ===
    LOG: This bind starts in default load context.
    LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe.Config
    LOG: Using host configuration file: 
    LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
    LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
    LOG: Attempting download of new URL file:///D:/x64Production.DLL.
    LOG: Assembly download was successful. Attempting setup of file: D:\x64Production.dll
    LOG: Entering run-from-source setup phase.
    LOG: Assembly Name is: x64Production, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
    ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

Has anyone else ascertained whether or not this is simply unsupported in the VS2010 mstest?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

半暖夏伤 2025-01-10 15:20:17

我来这里寻找类似问题的解决方案。发布此答案以防万一我找到的解决方案对其他人有帮助。
这在 Visual Studio (2012) 中为我解决了这个问题:

添加新项目 ->测试设置 添加测试设置项
更改测试设置 在 64 位进程中运行测试
默认情况下,此设置为“强制测试在 32 位进程中运行”

从菜单中:
测试->测试设置->选择测试设置文件->选择您创建的测试设置文件。

现在运行测试。

I came here searching for the solution for a similar problem. Posting this answer just in case the solution I found helps someone else.
This solved it for me in Visual Studio (2012):

Add New Item -> Test Settings Add Test Setting Item
Change the testsetting Run test in 64 bit process
By default this is set to "Force test to run in 32 bit process"

From the menu:
Test -> Test Settings -> Select Test Settings File -> Choose the test settings file you have created.

Now run the tests.

痴者 2025-01-10 15:20:17

另外,您可以进入菜单“测试”->“测试设置”->“默认处理器架构”->“X64”。它可能会起作用。

Also, you can go to menu Test->Test Settings->Default Procesor Architecture->X64. It may work.

烟织青萝梦 2025-01-10 15:20:17

现在使用 Visual Studio 2013(至少在 2012 年没有尝试过),我不需要做任何事情,只需选择“测试”->“测试设置”->“默认处理器架构”->x64。也可以使用测试设置文件来达到相同的结果。您在其他答案和网络上的各种帖子中看到的那些旧的克鲁格都没有必要。由于我的东西必须使用 x64,所以我也添加了这些测试用例,只是为了提醒我是否有一些设置错误。

    [TestMethod]
    public void Running_64Bit_OS()
    {
        // It was determined to run only in 64 bits.
        bool is64BitOS = System.Environment.Is64BitOperatingSystem;
        Assert.AreEqual(is64BitOS, true);
    }

    [TestMethod]
    public void Running_64Bit_Process()
    {
        // We have a requirement that one of the unmanaged DLL is built for 64 bits.
        // If you are running MS Test in Visual Studio 2013 and this
        // is failing, go to Test->Test Settings->Default Processor Architecture and
        // chose x64, then run the tests again.  This is not the only method.  You
        // could also use a test settings file.
        bool is64BitProcess = System.Environment.Is64BitProcess;
        Assert.AreEqual(is64BitProcess, true);
    }

Now with Visual Studio 2013 (at least, didn't try in 2012) I didn't have to do anything but choose Test->Test Settings->Default Processor Architecture->x64. Can also use test settings file to achieve the same result. None of those old kluges necessary that you see in other answers and various posting on the web. Since my stuff has to use x64, I added these test cases too just to remind me if I have some setting wrong.

    [TestMethod]
    public void Running_64Bit_OS()
    {
        // It was determined to run only in 64 bits.
        bool is64BitOS = System.Environment.Is64BitOperatingSystem;
        Assert.AreEqual(is64BitOS, true);
    }

    [TestMethod]
    public void Running_64Bit_Process()
    {
        // We have a requirement that one of the unmanaged DLL is built for 64 bits.
        // If you are running MS Test in Visual Studio 2013 and this
        // is failing, go to Test->Test Settings->Default Processor Architecture and
        // chose x64, then run the tests again.  This is not the only method.  You
        // could also use a test settings file.
        bool is64BitProcess = System.Environment.Is64BitProcess;
        Assert.AreEqual(is64BitProcess, true);
    }
南笙 2025-01-10 15:20:17

从本文中可以看出,MSTest.exe 是 32 位的。

注释:这是 Visual Studio 2010 的答案。现代系统会得到 64 位 MSTest.exe,如果尝试加载 32 位 dll,则会出现相反的问题。

From reading this, MSTest.exe is 32 bit.

Annotation: This is an answer for Visual Studio 2010. Modern systems get a 64 bit MSTest.exe and the opposite problem if they try to load 32 bit dlls.

ˇ宁静的妩媚 2025-01-10 15:20:17

就我而言,它似乎与 x86 或 x64 平台或测试配置设置或项目的 .NET 版本无关。顺便说一句,我得到的 BadImageFormatException 错误还提到了有关“签名不正确”的内容。

问题是,在使用 Moq 时,我们需要为依赖于我们尝试模拟的对象的类/接口添加对单元测试项目的缺失引用。查看您正在测试的项目的引用,以了解您可能缺少哪些与您正在模拟的对象相关的程序集。

http://vibrantcode.com/2012/05/18/ badimageformatException-签名不正确/

In my case, it seemed to have nothing to do with x86 or x64 platform or test configuration settings or the project's .NET version. BTW the BadImageFormatException error I got also mentioned something about 'the signature is incorrect'.

The issue was that when using Moq, we need to add missing references to the unit test project for classes/interfaces that are dependent of the object we are trying to mock. Look into the references of the project you are testing to get an idea of what assemblies you might be missing that are related to the object you are mocking.

http://vibrantcode.com/2012/05/18/badimageformatexception-the-signature-is-incorrect/

许一世地老天荒 2025-01-10 15:20:17

如果您安装了 ReSharper,请参阅以下内容 链接

基本上,您需要在解决方案中创建一个测试设置文件(如其他答案中所示),然后更新 MsTest 的 ReSharper 选项以指向相同的设置文件。

我使用 Visual Studio 2013 Update 4 和 Resharper 8.2 遇到了这个问题。

If you have ReSharper installed, refer to the following link

Basically, you need to create a test settings file in your solution as indicated in the other answers then update the ReSharper option for MsTest to point to the same settings file.

I cam across this issue using Visual Studio 2013 Update 4 and Resharper 8.2.

野心澎湃 2025-01-10 15:20:17

如何设置 MSTest 来测试 64 位程序集

除了有关此问题的其他回答者提供的 .testsettings 信息之外,此答案还涵盖了 Visual Studio 2015 和 Visual Studio 2017 早期版本的一些怪癖,此修复程序还可以适用于 Visual Studio 2013,但我没有可用于测试的机器。

1. 添加 .testsettings 文件

右键单击​​解决方案(不是单元测试项目),然后在“测试设置”类别下添加一个 .testsettings 文件。它可以命名为您想要的任何名称。

添加测试设置窗口屏幕截图


2. 配置 .testsettings 文件以使用 64 位进程

在出现的“测试设置”向导中,您唯一需要自定义的是在“主机”选项卡下,设置“跑步在 32 位或 64 位进程中进行测试”更改为“在 64 位计算机上在 64 位进程中运行测试”。当您在这里时,检查默认设置以确保它们有意义可能是个好主意。单击“应用”,完成后单击“关闭”。

测试设置配置窗口,显示在哪里将其设置为 64 位

现在您的 .testsettings 文件将显示在解决方案资源管理器中。

图像显示解决方案资源管理器中的测试设置文件


Visual Studio 2015 中错误的额外解决方法

  • Visual Studio 2017(使用版本 15.3.3 社区进行测试)似乎已采取步骤3和4不必要。我将把这些步骤留在这里,供那些使用旧版本 Visual Studio 的人使用,或者以防万一仍有办法重现该行为。

  • 在Visual Studio 2015中,如果你只是通过Test->设置默认的处理器架构测试设置->默认处理器架构 -> x64,Visual Studio 会忘记您的设置 (请参阅此错误报告)。这已在 Visual Studio 2015 Professional Update 3 中进行了测试。

  • 据我所知,在记住 CPU 架构方面,Visual Studio 2013 与 Visual Studio 2015 存在类似的错误。我还没有在 Visual Studio 2013 上测试过这个(我没有),但它可能值得一试。

3. 添加 .runsettings 文件,将测试设置为永久 64 位

打开记事本(或您选择的 XML 文件编辑器),并将其粘贴到其中。

<?xml version="1.0" encoding="utf-8"?>  
<RunSettings>  
    <!-- Configurations that affect the Test Framework -->  
    <RunConfiguration>  
        <!-- [x86] | x64 -->  
        <TargetPlatform>x64</TargetPlatform> 
    </RunConfiguration> 
</RunSettings> 

然后保存文件,我将其作为 DemoTest.runsettings 与 DemoTest.testsettings 一起保存在解决方案的目录中。

  • 请参阅使用 .runsettings 文件配置单元测试有关此文件的详细信息。

  • 注意:拥有一个仅包含此条目的 .runsettings 文件是安全的,因为...

    <块引用>

    文件的每个元素都是可选的,因为每个值都有默认值。

  • 我建议将 .runsettings 文件添加到您的解决方案中,以便开发人员可以在解决方案资源管理器中看到它,尽管这不会以任何方式影响功能。


4.加载您的.runsettings文件

在菜单栏中,单击测试->测试设置->选择测试设置文件

显示如何使用“测试”菜单加载测试设置文件的图像

选择您的runsettings 文件。不是您的测试设置文件。


现在您应该能够毫无问题地运行测试。

图像显示测试没问题

MSTest 限制

  • 请注意,MSTest 仅适用于编译为任何 CPU 的单元测试项目。 x64 测试项目不会在测试资源管理器下显示任何测试。

  • 要测试的程序集可以是x64,但单元测试库本身必须是Any CPU。

配置管理器显示单元测试库必须构建为 Any CPU

How to set up MSTest to test a 64 bit assembly

In addition to the .testsettings information provided by the other answerers on this question, this answer covers some of the quirks of Visual Studio 2015 and early versions of Visual Studio 2017, this fix may also work for Visual Studio 2013 but I don't have a machine available to test with for that.

1. Add a .testsettings file

Right click on the Solution (not the unit test project), then under the Test Settings category, add a .testsettings file. It can be named anything you want.

Add test settings window screenshot


2. Configure the .testsettings file to use a 64 bit process

In the "Test Settings" wizard that comes up, the only thing that you must customize is under the "Hosts" tab, set the "Run tests in 32 bit or 64 bit process" to "Run tests in 64 bit process on 64 bit machine". While you are here it may be a good idea to review the default settings to make sure they make sense. Click Apply, then Close when you are done.

Test settings configuration window, showing where to set it to 64 bit

Now your .testsettings file will show up in solution explorer.

Image showing the test settings file in the solution explorer


Extra Workaround for a bug in Visual Studio 2015

  • It seems like Visual Studio 2017 (tested using version 15.3.3 Community) has made steps 3 and 4 unnecessary. I will leave these steps here for those of you who are using older versions of Visual Studio, or in case there is still a way to reproduce the behavior.

  • In Visual Studio 2015, if you just set the default processor architecture through Test -> Test Settings -> Default Processor Architecture -> x64, Visual Studio will forget your setting (see this bug report). This was tested in Visual Studio 2015 Professional Update 3.

  • From what I have read, Visual Studio 2013 has a similar bug to Visual Studio 2015 when it comes to remembering CPU architecture. I haven't tested this on Visual Studio 2013 (I don't have it) but it might be worth a try.

3. Add a .runsettings file to set your tests to be permanently 64 bit

Open notepad (or your XML file editor of choice), and paste this into it.

<?xml version="1.0" encoding="utf-8"?>  
<RunSettings>  
    <!-- Configurations that affect the Test Framework -->  
    <RunConfiguration>  
        <!-- [x86] | x64 -->  
        <TargetPlatform>x64</TargetPlatform> 
    </RunConfiguration> 
</RunSettings> 

Then save the file, I saved it as DemoTest.runsettings in my solution's directory alongside DemoTest.testsettings.

  • Please see Configure unit tests by using a .runsettings file for more information about this file.

  • Note: It is safe to have a .runsettings file with just this entry in it, because...

    Each element of the file is optional, because every value has a default.

  • I recommend adding your .runsettings file to your solution, just so developers can see it in the Solution Explorer, though this does not affect functionality in any way.


4. Load your .runsettings file

In the menu bar, click Test -> Test Settings -> Select Test Settings File

Image showing how to load a test settings file using the Test menu

Select your runsettings file. Not your testsettings file.


Now you should be able to run your tests without issues.

image showing that the tests are okay

MSTest Limitations

  • Note that MSTest will only work with Unit Test Projects compiled as Any CPU. An x64 test project will not show any tests under Test Explorer.

  • The assembly to be tested can be x64, but the unit test library itself must be Any CPU.

Configuration manager showing that the unit test library must be built as Any CPU

淡淡離愁欲言轉身 2025-01-10 15:20:17

按照这篇博文,从 VS 运行以下内容命令提示符(因此 CorFlags.exe 在 PATH 中),为我的玩具解决方案运行测试:

@echo off
REM remove the 32Bit flag, forcing the executable to be 64-bit when run on a 64 bit os.
REM Expect the following output:
REM "
REM corflags : warning CF011 : The specified file is strong name signed.  Using /Force will invalidate the signature of this image and will require the assembly to be resigned.
REM "
CorFlags.exe "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe" /32BIT- /Force

REM skip the strong name verification, because the 32-bit flag was modified 
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\StrongName\Verification\MSTest,b03f5f7f11d50a3a /f

REM copy over registry keys to the 64-bit shadow registry.
REM Without the "{13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b}\Extensions" subkey, mstest will output
REM "
REM File extension specified '.dll' is not a valid test extension.
REM "
reg copy HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\EnterpriseTools\QualityTools\TestTypes HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\10.0\EnterpriseTools\QualityTools\TestTypes /s /f

这与真正的生产代码相比如何还有待观察。

Having followed this blog post, the following, run from a VS command prompt (so CorFlags.exe is in the PATH), gets the tests running for my toy solution:

@echo off
REM remove the 32Bit flag, forcing the executable to be 64-bit when run on a 64 bit os.
REM Expect the following output:
REM "
REM corflags : warning CF011 : The specified file is strong name signed.  Using /Force will invalidate the signature of this image and will require the assembly to be resigned.
REM "
CorFlags.exe "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe" /32BIT- /Force

REM skip the strong name verification, because the 32-bit flag was modified 
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\StrongName\Verification\MSTest,b03f5f7f11d50a3a /f

REM copy over registry keys to the 64-bit shadow registry.
REM Without the "{13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b}\Extensions" subkey, mstest will output
REM "
REM File extension specified '.dll' is not a valid test extension.
REM "
reg copy HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\EnterpriseTools\QualityTools\TestTypes HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\10.0\EnterpriseTools\QualityTools\TestTypes /s /f

It remains to be seen how this will fare against the real production code.

当梦初醒 2025-01-10 15:20:17

除了@Anupam解决方案之外,在VS2013上,您可以转到TEST>测试设置>默认处理器架构并在X86X64之间更改。这与选择测试设置文件几乎相同,只是您不需要仅指定测试平台的文件。

In addition to @Anupam solution, on VS2013, you can go to TEST > Test Settings > Default Processor Architecture and change between X86 and X64. It's almost the same as selecting a test settings file, except that you don't need the file for only specifying the test platform.

海的爱人是光 2025-01-10 15:20:17

错误的原因之一是
如果您在解决方案中引用另一个项目,请右键单击引用的项目,
选择应用程序选项卡,检查输出类型。如果输出类型是控制台应用程序切换到类库然后尝试运行。

One of the causes of the error is
If you reference another project in your solution right click to referenced project,
select Application tab, check Output type. If the Output type is Console Application switch to Class Library then try to run.

风柔一江水 2025-01-10 15:20:17

感谢 Resharper 的提示,因为它指出可以通过切换到 MSTest 来避免该问题。我无法让 Resharper 工作。测试 64 位第三方 64 位 DLL,即使您只是模拟它(仍然必须加载它),似乎也只能在 64 位模式下与 MsTest 一起使用。 MSTest 的“使用此测试运行配置”的 Resharper 选项只有“默认”作为下拉选项,“编辑”显示为灰色。另一个设置“使用元数据文件中指定的测试运行配置”也不起作用,这假设人们知道该元数据文件是什么或在哪里。正如上面的环境变量 Is64BitProcess 所证明的那样,Resharper 不会在 64 位模式下运行。 (VS 2013 更新 4、Resharper 8.2)

Thanks for the tip on Resharper, because it pointed out the problem could be avoided by switching to MSTest. I could not get Resharper to work. Testing a 64 bit third party 64 bit DLL even if you are only Mocking it (still have to load it) only appears to work with MsTest in 64 bit mode. The Resharper option for MSTest to "Use this Test Run Configuration" only has "Default" as a dropdown option and "Edit" is greyed out. The other setting "Use Test Run Configuration specified in metadata file" does not work either and this assumes one knows what or where this metadata file is. Resharper would not run in 64 bit mode as proved by the above Environment variable Is64BitProcess. (VS 2013 Update 4, Resharper 8.2)

挥剑断情 2025-01-10 15:20:17

对于 Visual Studio 2022,转到测试 ->适用于任何 CPU 的处理器架构 -> 选择有效的处理器架构,对于我来说,它是 32 位。

For visual studio 2022, Go to Test -> Processor Architecture For Any CPU ->Select the one which work, for my case it was 32 bit.

终难遇 2025-01-10 15:20:17

另一个答案的注释:现代系统会得到 64 位 MSTest.exe,如果尝试加载 32 位 dll,则会出现相反的问题。话虽如此,问题仍然存在,如果您尝试加载在 x86 上运行的project.dll,则会遇到该问题。如何使用 VS2022 修复此问题:

Visual Studio 2022

使用 .runsettings 文件配置单元测试

  1. 将运行设置文件添加到您的解决方案中。在“解决方案资源管理器”中,在解决方案的快捷菜单上,选择“添加”>新建项目,然后选择XML 文件。使用诸如 test.runsettings

    之类的名称保存文件

  2. 从中添加内容,并可选择根据您的需要对其进行自定义:

    <?xml version="1.0" encoding="utf-8"?>   
    <RunSettings>  
        <!-- Configurations that affect the Test Framework -->  
        <RunConfiguration>  
            <!-- x86 | x64 -->  
            <TargetPlatform>x86</TargetPlatform> 
        </RunConfiguration>  
    </RunSettings>
  1. 指定所需的 *.runsettings 文件。首选方式:设置构建属性。通过项目文件或 Directory.Build.props 文件将构建属性添加到项目。项目的运行设置文件由属性 RunSettingsFilePath 指定。为项目指定 .runsettings 文件的示例:
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <RunSettingsFilePath>$(MSBuildProjectDirectory)\example.runsettings</RunSettingsFilePath>
      </PropertyGroup>
      ...
    </Project>

注意: .runsettings 文件中仅包含此条目是安全的,因为...

  • 文件的每个元素都是可选的,因为每个值都有默认值。
  • 我建议将 .runsettings 文件添加到您的解决方案中,以便开发人员可以在解决方案资源管理器中看到它,但这不会以任何方式影响功能

有关详细信息,请参阅 使用.runsettings 文件

-- 或 --

手动选择处理器架构

从 Visual Studio 菜单中,选择测试,然后选择AnyCPU 项目的处理器架构。选择 x86 作为 32 位进程运行测试

注意:这是本地更改,不会影响 CI 管道等,它可能会测试您的代码。

Annotation from another answer: Modern systems get a 64 bit MSTest.exe and the opposite problem if they try to load 32 bit dlls. Saying that, the problem still occurs, if you try to load a project.dll running on x86, you got that problem. How to fix that with VS2022:

Visual Studio 2022

Configure unit tests by using a .runsettings file

  1. Add a run settings file to your solution. In Solution Explorer, on the shortcut menu of your solution, choose Add > New Item, and select XML File. Save the file with a name such as test.runsettings

  2. Add the content from this and optionally customize it to your needs:

    <?xml version="1.0" encoding="utf-8"?>   
    <RunSettings>  
        <!-- Configurations that affect the Test Framework -->  
        <RunConfiguration>  
            <!-- x86 | x64 -->  
            <TargetPlatform>x86</TargetPlatform> 
        </RunConfiguration>  
    </RunSettings>
  1. Specify the *.runsettings file that you want. Prefered way: Set a build property. Add a build property to a project through either the project file or a Directory.Build.props file. The run settings file for a project is specified by the property RunSettingsFilePath. Example of specifying a .runsettings file for a project:
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <RunSettingsFilePath>$(MSBuildProjectDirectory)\example.runsettings</RunSettingsFilePath>
      </PropertyGroup>
      ...
    </Project>

Note: It is safe to have a .runsettings file with just this entry in it, because...

  • Each element of the file is optional, because every value has a default.
  • I recommend adding your .runsettings file to your solution, just so developers can see it in the Solution Explorer, though this does not affect functionality in any way

For more infos see Configure unit tests by using a .runsettings file

-- or --

Choose Processor Architecture manually

From the Visual Studio menu, choose Test, then choose Processor Architecture for AnyCPU projects. Choose x86 to run the tests as a 32-bit process

Note: This is a local change and does not affect e.g. CI Pipelines, which may test your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文