如何在NUNIT中使用[TestCase]或[TestCaseSource]传递结构参数给测试函数

本文关键字:结构 参数 函数 测试 TestCaseSource NUNIT TestCase | 更新日期: 2023-09-27 18:07:39

我现在在实践TDD。我想通过使用[TestCase]或[TestCaseSource]属性来简化我糟糕的测试功能。请帮帮我。这是我现在的函数

    [Test]
    public void GetLength_TEST_1()
    {
        double output = Program.GetLength(new Point { x = 1, y = 2 }, new Point { x = 7, y = 8 });
        output *= 1000;
        output = Math.Truncate(output);
        output /= 1000;
        Assert.AreEqual(8.485, output);            
    }
    [Test]
    public void GetLength_TEST_2()
    {
        double output = Program.GetLength(new Point { x = 2, y = 7 }, new Point { x = -8, y = -6 });
        output *= 1000;
        output = Math.Truncate(output);
        output /= 1000;
        Assert.AreEqual(16.401, output);
    }

如何在NUNIT中使用[TestCase]或[TestCaseSource]传递结构参数给测试函数

使用TestCaseSource属性。

注意相同的测试方法应该执行两个测试用例。

如下所示

[TestFixture]
public class MyClass
{
    public class PointTestCase
    {
        public string TestName { get; private set; }
        public Point P1 { get; set; }
        public Point P2 { get; set; }
        public double Result { get; set; } 
        public PointTestCase(Point p1, Point p2, double result)
        {
            P1 = p1;
            P2 = p2;
            Result = result;
        }
        public override string ToString()
        {
            return TestName;
        }
    }
    private static IEnumerable<PointTestCase> PointTestCases
    {
        get
        {
            yield return new PointTestCase(new Point { x = 1, y = 2 }, new Point { x = 7, y = 8 }, 8);
            yield return new PointTestCase(new Point { x = 2, y = 7 }, new Point { x = -8, y = -6 }, -12);
        }
    }
    [Test, TestCaseSource("PointTestCases")]
    public void GetLength_TEST(PointTestCase pointTestCase)
    {
        double output = Program.GetLength(pointTestCase.P1, pointTestCase.P2);
        output *= 1000;
        output = Math.Truncate(output);
        output /= 1000;
        Assert.AreEqual(pointTestCase.Result, output);
    }
}
public static class Program
{
    public static double GetLength(Point p1, Point p2)
    {
        //some logic/calculation
        return p1.x * p2.y;
    }
}
public class Point
{
    public double x { get; set; }
    public double y { get; set; }
}