如何从Visual Studio以调试模式运行NUnit?

时间:2013-05-31 20:31:55

标签: c# visual-studio-2010 selenium nunit typeinitializeexception

要在NUnit中使用调试模式,我添加了一个在线模板“NUnit Test application”。所以当我添加一个新项目时,我选择NUnit测试应用程序而不是类库。创建项目时,会自动添加两个.cs文件。我添加了一个简单的程序来检查调试模式并显示错误。如何纠正这个错误?谢谢。

TypeInitializationException was unhandled.

错误发生在

int returnCode = NUnit.ConsoleRunner.Runner.Main(my_args);

自动添加的文件是 Program.cs的

namespace NUnitTest1
{
    class Program
    {
       [STAThread]
       static void Main(string[] args)
       {
         string[] my_args = { Assembly.GetExecutingAssembly().Location };
         int returnCode = NUnit.ConsoleRunner.Runner.Main(my_args);

         if (returnCode != 0)
            Console.Beep();
       }
    }
 }

TestFixture.cs

namespace NUnitTest1
{
   [TestFixture]
   public class TestFixture1
    {
      [Test]
      public void TestTrue()
      {
        Assert.IsTrue(true);
      }

    // This test fail for example, replace result or delete this test to see all tests pass
      [Test]
      public void TestFault()
      {
        Assert.IsTrue(false);
      }
    }
  }

我为它添加了一个新的项目类并尝试调试

namespace NUnitTest1
{
   [TestFixture]
    public class Class1
    {
        IWebDriver driver = null;
        [SetUp]
        public void setup()
        {
           //set the breakpoint here
            driver = new FirefoxDriver();
        }
        [Test]
        public void test1()
        {
            driver.Navigate().GoToUrl("http://www.google.com/");                
        }
        [TearDown]
        public void quit()
        {
            driver.Quit();
        }
      }
   }

3 个答案:

答案 0 :(得分:3)

正如@Arran已经提到的,你真的不需要做这一切。但是,您可以更轻松地调试NUnit测试。

在Visual Studio中使用F5调试单元测试

不是执行NUnit运行器并使用Visual Studio附加到进程,最好配置yout测试项目以启动NUnit测试运行器并调试测试。您所要做的就是按照以下步骤操作:

  1. 打开测试项目的属性
  2. 选择调试标签
  3. 开始操作设置为启动外部程序并指向NUnit runner
  4. 设置命令行参数
  5. 保存项目属性
  6. 你已经完成了。点击 F5 ,您的测试项目将以NUnit运行程序执行的调试模式启动。

    您可以在我的blog post中了解相关信息。

答案 1 :(得分:1)

你根本不需要做这一切。

打开NUnit GUI,打开已编译的测试。在Visual Studio中,使用Attach to Process功能附加nunit-agent.exe。

在NUnit GUI中运行测试。 VS调试器将从那里获取它。

答案 2 :(得分:1)

你需要付出太多努力才能完成这项工作。

我通常做的是创建一个新的“类库”项目。然后我在我的项目中添加对nunin-framework.dll的引用。

您可以按如下方式定义您的课程:

[TestFixture]
public class ThreadedQuery
{
    [Test]
    public void Query1()
    {

    }
}

TestFixture属性描述为here

然后,您可以继续使用上述公共方法创建多个测试。

有三件事对于让这个工作变得非常重要。

  1. 您需要将项目文件上的调试器设置为外部可执行文件,即nunint.exe
  2. 传递的参数必须是程序集的名称。
  3. 如果您正在使用.net 4.0,则需要在nunint.exe.config中指定 如果不这样做,您将无法使用VS进行调试。请参阅下面的配置代码段:

    <startup useLegacyV2RuntimeActivationPolicy="true">
        <!-- Comment out the next line to force use of .NET 4.0 -->
        <!--<supportedRuntime version="v2.0.50727" />-->
        <supportedRuntime version="v4.0.30319" />
        <supportedRuntime version="4.0" />
    </startup>
    
  4. 希望这是有帮助的