Visual studio with xUnit, Assert.Throws and "Exception was unhandled by user code"



我正在尝试使用xUnit 1.8.0.1549在dll应用程序(VS2010/c#)内运行测试。为此,我通过visual studio在项目属性的"Start Action"下使用"Start External Program"运行xUnit,通过GUI运行器(C:mypath xUnit . GUI .clr4.x86.exe)运行dll。

我想测试一些方法是否会引发异常,为此,我使用如下代码:

Assert.Throws<Exception>(
   delegate
   {
       //my method to test...
       string tmp = p.TotalPayload;
   }
);

问题是调试器停止,在我的方法中,当异常被抛出时说"异常未被用户代码处理"时。这很糟糕,因为它会一直停止gui运行程序,迫使我按F5。我想顺利地运行测试,我该怎么做?由于

您可以在vs中关闭异常行为的中断,参见http://msdn.microsoft.com/en-us/library/d14azbfh.aspx获取灵感。

如果你进入Visual Studio选项并取消选中"Just my code"设置,xUnit框架将被视为用户代码,并且那些异常(xUnit期望的)不会提示你。

我不知道如何控制每个程序集的这种行为(只考虑xUnit是用户代码,而不是其他外部代码)。

当您检查异常是否发生时,您将不得不在单元测试代码中处理异常。现在,你没有那样做。

下面是一个例子:我有一个方法,读取文件名,并做一些处理:

  public void ReadCurveFile(string curveFileName)
    {           
        if (curveFileName == null) //is null
            throw new ArgumentNullException(nameof(curveFileName)); 
        if (!File.Exists(curveFileName))//doesn't exists
            throw new ArgumentException("{0} Does'nt exists", curveFileName);     

…等现在我编写一个测试方法来测试这段代码,如下所示:

    [Fact]
    public void TestReadCurveFile()
    {
        MyClass tbGenTest = new MyClass ();
        try
        {
            tbGenTest.ReadCurveFile(null);
        }
        catch (Exception ex)
        {
            Assert.True(ex is ArgumentNullException);
        }
        try
        {
            tbGenTest.ReadCurveFile(@"TestDataPCMTestFile2.csv");
        }
        catch (Exception ex)
        {
            Assert.True(ex is ArgumentException);
        }

相关内容

最新更新