【问题标题】:How do I pass an Action into a TestCase如何将 Action 传递到 TestCase
【发布时间】:2013-12-19 21:25:20
【问题描述】:

我有一个 NUnit 测试

[TestCase(...)]
public void test_name(Action onConfirm)
{
   ...
}

我想要做的是在 TestCase 属性中将一个 Action 传递给这个测试,但无论我尝试什么都会失败。我试着把

() => SomeDummyMethodIDefined()

直接进入 TestCase 并没有用。

我创建了一个动作

Action DummyAction = () => SomeDummyMethodIDefined();

并将 DummyAction 传递到 TestCase 中,但没有成功。

有没有办法做到这一点?

【问题讨论】:

    标签: nunit


    【解决方案1】:

    这是一个非常粗略的例子,我从阅读 NUnit docs here 得到启发

    namespace NUnitLambda
    {
        using System;
        using NUnit.Framework;
    
        [TestFixture]
        public class Class1
        {
            [Test]
            [TestCaseSource(typeof(SourceClass), "TestCases")]
            public void Foo(Action action)
            {
                action();
            }
        }
    
        public class SourceClass
        {
            private static Action t = () => Console.WriteLine("Hello World");
    
            public static Action[] TestCases = { t };
        }
    }
    

    试一试代码,希望你能从中得到你想要的。作为记录,我使用的是 NUnit 2.6。

    编辑:

    您也不必在此处使用static,例如

    public class SourceClass
    {
        private Action t = () => Console.WriteLine("Hello World");
    
        public Action[] TestCases;
    
        public SourceClass()
        {
            TestCases = new Action[1];
    
            TestCases[0] = t;
        }
    }
    

    【讨论】:

    • 非常感谢!在 C# 6.0 中,您可以使用 nameof(SourceClass.TestCases) 使其成为强类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多