2015-06-01 46 views
0

我试图从控制台应用程序使用反射运行nunit测试用例。我得到一个异常,这是我的catch块没有处理的。你能否给出一个建议如何处理调用的测试方法中的所有异常?从控制台应用程序运行nunit测试时处理异常

static void Main(string[] args) 
{ 
    // Take all classes of the current assebly to which TestFixture attribute is applied 
    var testClasses = Assembly.GetExecutingAssembly().GetTypes().Where(c => 
    { 
     var attributes = c.GetCustomAttributes(typeof(TestFixtureAttribute)); 
     return attributes.Any(); 
    }); 
    foreach (var testClass in testClasses) 
    { 
     var testMethods = testClass.GetMethods().Where(m => 
     { 
      var attributes = m.GetCustomAttributes(typeof (TestAttribute)); 
      return attributes.Any(); 
     }); 
     var instance = Activator.CreateInstance(testClass); 
     foreach (var method in testMethods) 
     { 
      try 
      { 
       Action action = (Action) Delegate.CreateDelegate(typeof (Action), 
                   instance, method); 
       action(); 
      } 
      catch (AggregateException ae) 
      { 
       Console.WriteLine(ae.Message); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.Message); 
      } 
     } 
    } 
} 
+0

聚集异常发生在try块中,未被捕获。 – Salkony

+2

什么是异常的堆栈跟踪,以及它是哪种类型,异常的消息是什么? –

回答

0

这真的不清楚为什么你要做到这一点,因为已经有可以从一个控制台应用程序运行单元测试NUnit控制台。目前还不清楚你认为什么异常被捕获,但我怀疑这不是你认为的那种类型。我把你的代码,并把它变成一个新的控制台应用程序,有一些非常基本的测试一起:

[TestFixture] 
public class SomeFailingTests 
{ 
    [Test] 
    public void Fails() 
    { 
     Assert.AreEqual(1, 0); 
    } 

    [Test] 
    [ExpectedException(typeof(ArgumentException))] 
    public void TestExceptionExpected() 
    { 
    } 

    [Test] 
    public void TestThrows() 
    { 
     throw new InvalidOperationException(); 
    } 

    [Test] 
    [ExpectedException(typeof(InvalidOperationException))] 
    public void TestThrowsExpected() 
    { 
     throw new InvalidOperationException(); 
    } 
} 

所有抛出的异常是由线抓住了测试:

catch (Exception e) 

这是有道理的,因为他们都没有投掷AggregateException。我怀疑你运行的是哪一项测试也没有投掷,并且也被你的外线抓住。一个良好的开端可能是此块改写为:

catch (Exception e) 
{ 
    Console.WriteLine(string.Format("{0}: {1}", e.GetType().Name, e.Message)); 
} 

所以,你可以看到你不处理任何异常类型。例如,在非常基础的层面上,您可能必须考虑AssertionException

如果您希望支持与其他nunit跑步者相似的功能,您还需要注意您运行的任何方法的ExpectedException属性,并检查当您调用方法时是否引发该异常。您还需要检查的Ignored属性...

正如在我的答案被提到this question,你可能还需要注意其他测试属性,如TestCaseTestCaseSource如果你想捕捉装配中所有测试的

除非您将此作为学习练习,否则您可能需要重新考虑您的方法。

相关问题