2016-05-29 58 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

相關問題