动态创建测试用例

时间:2021-03-22 14:22:32

标签: c# testing nunit

我有一个包含多个测试用例的 JSON 文件,如下所示:

{
    "cases":[
        {
            "case": "TestCas1",
            "input": "x=y",
            "result": {
                "type": "Eq",
                "lhs": "x",
                "rhs": "y"
            }
        },
        { 
        //etc
        }
    ]
}

我想粗略地生成如下内容:


   [Test]
   [TestCase("x=y", "x", "y", "Eq")]
   /// Other test cases from file go here.
   public void Test(string input, string lhs, string rhs, string op)

现在,我知道如何解析和处理文件,以及如何编写测试,但是如何根据处理后的数据生成 TestCase?

1 个答案:

答案 0 :(得分:1)

您应该使用 TestCaseSourceAttribute 指向生成测试用例的方法。文档中描述了几种使用它的方法。以下是典型...

public class MyTestFixture
{
    [TestCaseSource(nameof(MyTestCases))]
    public void MyTestMethod(string input, string lhs, string rhs, string op)
    {
        // Your test code here
    }

    static IEnumerable<TestCaseData> MyTestCases()
    {
        foreach (var item in your json file) // pseudocode
        {
            // Get the four argument values

            yield return new TestCaseData(input, lhs, rhs, op);
        }
    }
}
相关问题