我在 Visual Studio 2010 (.NET 4) 中有一个单元测试项目,它利用 xUnit.net 测试框架、Moq 和 Moles Isolation 框架来生成静态方法的存根。我在 64 位机器上使用 xUnit 1.9 版。
要从命令行运行测试,我使用以下命令:
moles.runner.exe Project.Tests.dll /runner:xunit.console.clr4.exe
但是,我每次都会遇到以下异常:
检测...启动 xUnit.net 控制台测试运行程序(64 位 .NET 4.0.30319.1)版权所有 (C) 2007-11 Microsoft Corporation。
未处理的异常:System.MethodAccessException:尝试通过安全透明方法“Xunit.ConsoleClient.Program.Main(System.String[])”访问安全关键方法“System.AppDomain.add_UnhandledException(System.UnhandledExceptionEventHandler)”失败。在 Xunit.ConsoleClient.Program.Main(String[] args) 在 Microsoft.Moles.Runner.MolesRunner.Runner.Run(String runner, String[] args) 在 Microsoft.Moles.Runner.MolesRunner.RunnerRunner.Run(String runner , String[] args) 在 Microsoft.Moles.Runner.MolesRunner.LaunchRunnerEntryPoint(MolesRunnerOptions options) 在 Microsoft.Moles.Runner.MolesRunner.RunnerMain(String[] args) 在 Microsoft.Moles.Runner.Program.Main(String[]参数)
看起来异常来自 xUnit;但是,我可以单独使用 xunit.console.clr4.exe 运行测试而不会出现问题。只有在使用 Moles 跑步者的 xUnit 控制台时才会失败。
我在论坛帖子中找到了这个:
在 .NET 4 框架中,安全透明规则防止任何安全透明代码调用安全关键代码。
我可以检查什么来确定此错误的原因?我需要更改安全设置以防止这种情况吗?
注意:我在 32 位工作站上也遇到了同样的问题。
更新:我决定从http://xunit.codeplex.com/SourceControl/changeset/changes/600246119dca下载代码并自己调试。在 xunit.console 项目(其输出是从 Moles 运行器调用的 exe)中,执行的主线程如下所示:
[STAThread]
public static int Main(string[] args)
{
Console.WriteLine("xUnit.net console test runner ({0}-bit .NET {1})",
IntPtr.Size * 8, Environment.Version);
Console.WriteLine("Copyright (C) 2007-11 Microsoft Corporation.");
if (args.Length == 0 || args[0] == "/?")
{
PrintUsage();
return -1;
}
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
try
{
CommandLine commandLine = CommandLine.Parse(args);
int failCount = RunProject(commandLine.Project,
commandLine.TeamCity, commandLine.Silent);
if (commandLine.Wait)
{
Console.WriteLine();
Console.Write("Press any key to continue...");
Console.ReadKey();
Console.WriteLine();
}
return failCount;
}
catch (ArgumentException ex)
{
Console.WriteLine();
Console.WriteLine("error: {0}", ex.Message);
return -1;
}
catch (BadImageFormatException ex)
{
Console.WriteLine();
Console.WriteLine("{0}", ex.Message);
return -1;
}
}
当我在调试代码时运行测试时,一切正常,正如预期的那样(因为我从来没有单独从 xUnit 运行测试时遇到问题)。我注意到以下行,这似乎是根据我原始帖子中的错误消息和堆栈跟踪引发异常的地方:
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
我注释掉了这一行,构建了xunit.console.exe,并尝试在再次执行 Moles 运行器时将其用作/runner参数。这一次,没有抛出异常。
我仍然不知道为什么从 moles.runner.exe 调用时会在此行上引发安全异常,但当我自己运行 xUnit 控制台时却没有。