混合模式程序集 MSTest 在 VS2015 中失败

Mixed-Mode Assembly MSTest Failing in VS2015

当尝试 运行 在 VS2015 中使用混合模式程序集的单元测试时,测试无法执行并显示通常的消息:

System.IO.FileLoadException: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

创建 app.config 并向其添加 useLegacyV2RuntimeActivationPolicy 没有任何效果 - 似乎此配置无法更改。

这以前在 VS2013 中无需手动步骤即可工作。

备选方案 1:配置

将启动配置添加到C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config:

<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>

备选方案 2:在运行时

这可能会停止工作。

只需将此 class 添加到单元测试项目 (source):

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public static class RuntimePolicyHelper
{
    [AssemblyInitialize]
    public static void SetPolicy(TestContext ctx)
    {
        var clrRuntimeInfo =
            (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
                Guid.Empty,
                typeof(ICLRRuntimeInfo).GUID);

        // Allow errors to propagate so as to fail the tests.
        clrRuntimeInfo.BindAsLegacyV2Runtime();
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
    private interface ICLRRuntimeInfo
    {
        void xGetVersionString();
        void xGetRuntimeDirectory();
        void xIsLoaded();
        void xIsLoadable();
        void xLoadErrorString();
        void xLoadLibrary();
        void xGetProcAddress();
        void xGetInterface();
        void xSetDefaultStartupFlags();
        void xGetDefaultStartupFlags();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void BindAsLegacyV2Runtime();
    }
}