【问题标题】:Unit Test with input parameter带输入参数的单元测试
【发布时间】:2020-12-27 14:13:55
【问题描述】:

如何将方法作为参数调用到TestCase属性NUnit中?

就像我们可以这样写:[TestCase(1, 2, 3)]

如何调用如下函数?: [TestCase(SomeFunction(), 1, 2, 3)]

【问题讨论】:

    标签: c# .net .net-core nunit moq


    【解决方案1】:

    您可以尝试 TestCaseSource 属性并为您的用例使用静态方法。

        public static IEnumerable<EditModel> Generator()
        {
            // You can also call methods here
            yield return new EditModel();
        }
    
        [Test]
        [TestCaseSource(nameof(Generator))]
        public void DoSomething(EditModel model)
        {
            Console.WriteLine($"{model.commentText}");
        }
    

    【讨论】:

    • 为什么它应该是一个迭代器块?我只想退回一个模型。 `` public static EditModel CreateEditModel() { yield return new TestCaseData(new EditModel() { percent = 1.0M, count = 2345, commentText = "Comment Text", countryCode = "IND", countryEditID = 1, createdBy = "System" , createdDate = DateTime.Now,criteriaId = 1 }); } ``
    • 这是使用预定义数据调用测试方法的一种方式。您可以返回仅包含一个必要模型的模型列表。
    • 好的,这解决了我的问题,我可以像下面这样吗? [TestCaseSource(nameof(Generator), nameof(otherfunction1), nameof(otherfunction2))]
    • 你可以从你的方法返回complex类型。您可以有 IEnumerable(或 object []) 返回类型。请参阅documentation 第 1 段。
    【解决方案2】:

    要扩展上面的答案,您还可以尝试 TestCaseSource 属性并为您的测试用例实现一个工厂类。

    public class MyFactoryClass
    {
        public static IEnumerable TestCases
        {
            get
            {
                yield return new TestCaseData(MyMethod()).Returns(expectedTestResult);
                ....
            }
        }
    
        public EditModel MyMethod()
        {
            // Put method code here
            
            return editModel;
        }
    }
    
    public class MyTests
    {
        [Test,TestCaseSource(typeof(MyFactoryClass),"TestCases")]
        public void DoSomething(EditModel model)
        {
            // Test code here.
        }
    
        ...
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多