2016-05-29 79 views
1

我有大量的类似测试,我使用MemberData属性作为理论实现。我如何导航到每个堕落的测试用例并进行调试?如何在xunit测试中调试理论

下面的例子:

public const int A = 2; 
    public const int B = 3; 
    public const int C = 2; 

    public static IEnumerable<object[]> GetTestCases 
    { 
     get 
     { 
      // 1st test case 
      yield return new object[] 
      { 
       A, B, 4 
      }; 

      // 2nd test case 
      yield return new object[] 
      { 
       A, C, 4 
      }; 
     } 
    } 

    [Theory] 
    [MemberData("GetTestCases")] 
    public void TestMethod1(int operand1, int operand2, int expected) 
    { 
     // Q: How can I debug only test case, which is failed? 
     //...and break execution before exception will be raised 
     var actual = operand1 + operand2; 
     Assert.Equal(actual, expected); 
    } 

回答

0

好了,你可以在TestMethod1设置条件断点,并试图找到倒下的测试用例。但在很多情况下它并不那么舒服。

一个窍门可以帮助在这里:

public const int A = 2; 
    public const int B = 3; 
    public const int C = 2; 

    public static IEnumerable<object[]> GetTestCases 
    { 
     get 
     { 
      // 1st test case 

      // This line will be in stack trace if this test will failed 
      // So you can navigate from Test Explorer directly from StackTrace. 
      // Also, you can debug only this test case, by setting a break point in lambda body - 'l()' 
      Action<Action> runLambda = l => l(); 

      yield return new object[] 
      { 
       A, B, 4, 
       runLambda 
      }; 


      // 2nd test case 

      runLambda = l => l(); 

      yield return new object[] 
      { 
       A, C, 4, 
       runLambda 
      }; 

      // ...other 100500 test cases... 
     } 
    } 

    [Theory] 
    [MemberData("GetTestCases")] 
    public void TestMethod1(int operand1, int operand2, int expected, Action<Action> runLambda) 
    { 
     // pass whole assertions in a callback 
     runLambda(() => 
     { 
      var actual = operand1 + operand2; 
      Assert.Equal(actual, expected); 
     }); 
    } 

想法是把目标逻辑和断言进入回调,并调用它通过在每个测试用例注入一种特殊的类似lambda表达式。每个lambda将作为参数传递并在测试方法中调用,因此它将出现在堆栈跟踪中。当某个测试用例会掉落时,您可以通过点击相应的行来轻松地通过StackTrace导航到它(在本例中,它将看起来像'at UnitTestProject1.ExampleTests2。<> c.b__4_0(Action l)')

此外,您可以在该测试用例的lambda内设置断点,您要调试该错误并查看数据发生了什么。

+0

这也取决于你使用哪个IDE,因为每个扩展都有必要的支持让你通过IDE集成轻松调试一个理论。 –

+1

我使用Visual Studio和ReSharper。但他们不能(或者我没有找到如何)导航到代码行,在这里定义了选定测试用例的数据。你可以推荐这样的xUnit扩展吗? – Win4ster