【问题标题】:xUnit: Passing object containing reference to static fields as theoryxUnit:传递包含对静态字段的引用的对象作为理论
【发布时间】:2019-11-14 20:31:57
【问题描述】:

我将测试返回二维数组中单元格的冯诺依曼邻居数组的函数。 单元格包含有关模拟的数据。

为了进行测试,我设置了新的 Cell[,] 并填充了 Cell 实例。 测试应该检查函数返回的邻居是否与预期的实例相同,并且在数组中的顺序相同。

public class VonNeumanNeighbourhoodTest
{
    private static Cell a,b,c,d,e,f,g,h,i ;    
    private static Cell[,] space;

    public VonNeumanNeighborhoodTest() {
        a = new Cell{ GrainMembership = new Grain(0, Color.Red) };
        b = new Cell{ GrainMembership = new Grain(1, Color.Green) };
        // And so on 
        i = new Cell{ GrainMembership = new Grain(8, Color.Azure) };

        space = new Cell[3, 3]
            {
                { a, b, c },
                { d, e, f },
                { g, h, i }
        };
    }

问题出现在测试方法中。 Cell[] expected 在调试中总是包含 {null, null, null, null} 而不是 eg.{b, f, h, d} 参考。

    [Theory]
    [ClassData(typeof(AbsorbingTestData))]
    public void AbsorbingTest(int x, int y, Cell[] expected)
    {
        var neighbours = VonNeumanNeighbourhood.Neighbours(space , x, y, AbsorbingBoundary.BoundaryCondition);
        for(int i = 0; i < 4; i++)
        {
                Assert.Same(neighbours[i], expected[i]);//Checking if neighbours and expected are this same instances
            }
        }

    }
private class AbsorbingTestData : IEnumerable<object[]>
        {   
            public IEnumerator<object[]> GetEnumerator()
            {
                yield return new object[] { 1, 1, new Cell[]{b, f, h, d} }; //e - center
                yield return new object[] { 0, 0, new Cell[]{null, b, d, null} }; //a
                //More cases
            }

            IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
            }

    }

我正在尝试使用 [MemberData] 属性的类似代码,但结果相同。

【问题讨论】:

    标签: c# xunit xunit.net


    【解决方案1】:

    我认为您遇到了初始化顺序问题。 Cell 实例 (private static Cell a,b,c,d,e,f,g,h,i;) 是静态的,但由实例构造函数初始化。无法保证构造函数会在 xUnit 枚举测试用例之前运行。

    尝试用静态初始化程序 (static VonNeumanNeighborhoodTest()) 替换实例构造函数 (public VonNeumanNeighborhoodTest())。不过要小心——使用静态初始化器,这些值不会在测试之间重新设置。您最好寻找一种方法来完全消除 static 的使用。

    【讨论】:

    • 在将 VonNeumanNeighborhoodTest() 设置为静态并抛出构造函数后,它似乎可以工作。事实上,单元格在测试期间不会改变,所以我不需要在构造函数中重置它们。我试图在 AbsorbingTestData.GetEnumerator() 和构造函数中设置断点 - 只有被调用的代码是构造函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多