我正在使用Visual Studio 2015 Enterprise RTM编写单元测试,针对一个使用Unity容器的项目。
我发现即使不实际使用伪造程序集,只是添加 Unity 的伪装程序集就足以生成以下异常:
System.InvalidProgramException:公共语言运行时检测到无效程序。
请按照以下步骤重现此问题:
使用 Visual Studio 2015 Enterprise RTM 创建 .NET 4.6 单元测试项目
添加 NuGet 包“Unity”版本3.5.1404.0
添加 NuGet 包“CommonServiceLocator”版本1.2.0
编写一个单元测试,如下所示:
[TestClass]
public class UnitTest1 : IDisposable
{
[TestMethod]
public void TestMethod1()
{
new ResolvedArrayParameter<IDisposable>(new IDisposable[] {this});
}
void IDisposable.Dispose()
{
}
}
验证测试是否通过
右键单击 Microsoft.Practices.Unity 引用,选择“添加伪装程序集”
重新运行测试
观察以下异常测试失败:
测试名称: TestMethod1
测试全名: UnitTestProject11.UnitTest1.TestMethod1
测试源: c:\temp\UnitTestProject11\UnitTestProject11\UnitTest1.cs : line 12
测试结果: 失败
测试持续时间: 0:00:00.0572447结果堆栈跟踪:
at Microsoft.Practices.Unity.ResolvedArrayParameter..ctor(Type arrayParameterType, Type elementType, Object[] elementValues)
at Microsoft.Practices.Unity.ResolvedArrayParameter`1..ctor(Object[] elementValues)
at UnitTestProject11.UnitTest1.TestMethod1() in c:\temp\UnitTestProject11\UnitTestProject11\UnitTest1.cs:line 13
结果消息:
测试方法 UnitTestProject11.UnitTest1.TestMethod1 引发异常:
System.InvalidProgramException: Common Language Runtime detected an invalid program.
这个问题最不寻常的特点显然是即使在代码中没有直接出现伪装,故障仍会出现。
进行了大量试验后发现,将测试项目重新定位到 .NET 4.5 就可以“解决”问题,但这对我来说是不可行的,因为我之前发布了一个其他问题。
即使使用几乎所有伪装设置(代码合同等)也没有找到解决方案。
非常感谢您在此问题上提供的任何建议。