C# 如何调试xunit测试中的理论
我有大量类似的测试,我使用MemberData属性作为理论来实现这些测试。如何导航到每个失败的测试用例并对其进行调试 这里有一个例子:C# 如何调试xunit测试中的理论,c#,unit-testing,xunit,C#,Unit Testing,Xunit,我有大量类似的测试,我使用MemberData属性作为理论来实现这些测试。如何导航到每个失败的测试用例并对其进行调试 这里有一个例子: public const int A = 2; public const int B = 3; public const int C = 2; public static IEnumerable<object[]> GetTestCases { get {
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);
}
public const int A=2;
公共常数int B=3;
公共常数int C=2;
公共静态IEnumerable GetTestCases
{
得到
{
//第一个测试用例
返回新对象[]
{
A、 B,4
};
//第二个测试用例
返回新对象[]
{
A、 C,4
};
}
}
[理论]
[成员数据(“GetTestCases”)]
public void TestMethod1(整数操作数1、整数操作数2、预期整数)
{
//问:我如何只调试失败的测试用例?
//…并在引发异常之前中断执行
实际变量=操作数1+操作数2;
断言。相等(实际、预期);
}
好的,您可以在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);
});
}
public const int A=2;
公共常数int B=3;
公共常数int C=2;
公共静态IEnumerable GetTestCases
{
得到
{
//第一个测试用例
//如果此测试失败,此行将在堆栈跟踪中
//因此,您可以直接从StackTrace从测试资源管理器进行导航。
//另外,通过在lambda body中设置断点--“l()”可以只调试这个测试用例
操作runLambda=l=>l();
返回新对象[]
{
A、 B,4,,
朗姆达
};
//第二个测试用例
runLambda=l=>l();
返回新对象[]
{
A、 C、4、,
朗姆达
};
//…其他100500个测试用例。。。
}
}
[理论]
[成员数据(“GetTestCases”)]
public void TestMethod1(整数操作数1、整数操作数2、预期整数、操作runLambda)
{
//在回调中传递整个断言
runLambda(()=>
{
实际变量=操作数1+操作数2;
断言。相等(实际、预期);
});
}
其思想是将目标逻辑和断言放入回调中,并通过在每个测试用例中注入的特殊类似lambda调用它。每个lambda都将作为参数传递并在测试方法中调用,因此它将出现在堆栈跟踪中。当某个测试用例落下时,您可以通过单击相应的行轻松地通过StackTrace导航到它(在本例中,它看起来像“在UnitTestProject1.ExampleTests2.c.b_u4_0(操作l)”)
此外,您还可以在测试用例的lambda内部设置断点,您希望调试该断点并查看数据发生了什么。这还取决于您使用的IDE,因为每个测试用例的xunit扩展都有必要的支持,可以通过IDE集成轻松调试理论。我使用Visual Studio和ReSharper。但他们无法(或者我找不到如何)导航到代码行,在代码行中定义了所选测试用例的数据。你能推荐这样的xUnit扩展吗?