Search code examples
c#unit-testingxunit

How to debug theories in xunit tests


I have big amount of similar tests which I implement as a theory using MemberData attribute. How can I navigate to each fallen test case and debug it?

Here an example:

    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);
    }

Solution

  • This is quite an old question now but I came across it looking for an answer. I didn't really get the existing answer. Here is my solution:

        public static IEnumerable<object[]> GetTestCases()
        {
            int i = 1;
            yield return new object[] { i++, A, B, 4 };
            yield return new object[] { i++, A, C, 4 };
        }
    
        [Theory]
        [MemberData(nameof(GetTestCases)]
        public void TestMethod1(int textIndex, int operand1, int operand2, int expected)
        {
            // Test code here.
            // Use a conditional break point with the textIndex of the target test case
        }
    
    

    If you need to break point into the code under test place all those break points in a single group so you can enable/disable them together, have them initially disabled. Just have the above conditional break point enabled. Once the debugger hits that break point, enable your break point group and continue.