【问题标题】:Passing parameters to TestDelegate in NUnit在 NUnit 中将参数传递给 TestDelegate
【发布时间】:2013-01-02 09:38:24
【问题描述】:

我正在尝试创建一个采用 testdelegate 或委托并将参数传递给委托对象的方法。这是因为我正在为所有采用相同参数(一个 id)的控制器中的方法创建测试,并且我不想为所有控制器方法创建测试。

我的代码:

protected void AssertThrows_NullReference_Og_InvalidOperation(TestDelegate delegateMethod)
{

    Assert.Throws<NullReferenceException>(delegateMethod);
    Assert.Throws<InvalidOperationException>(delegateMethod);
    Assert.Throws<InvalidOperationException>(delegateMethod);
} 

我想做什么:

protected void AssertThrows_NullReference_Og_InvalidOperation(TestDelegate delegateMethod)
{

    Assert.Throws<NullReferenceException>(delegateMethod(null));
    Assert.Throws<InvalidOperationException>(delegateMethod(string.Empty));
    Assert.Throws<InvalidOperationException>(delegateMethod(" "));
} 

编辑: 我忘了提到控制器有一个返回值。因此不能使用 Action。

【问题讨论】:

  • 你是对的。我在底部添加了我自己的解决方案,我借用了你的代码并做了一些调整。感谢您的帮助。

标签: c# unit-testing delegates nunit


【解决方案1】:

使用Action&lt;string&gt; 传递接受单个字符串参数的方法。使用您的测试参数调用该操作:

protected void AssertThrowsNullReferenceOrInvalidOperation(Action<string> action)
{
    Assert.Throws<NullReferenceException>(() => action(null));
    Assert.Throws<InvalidOperationException>(() => action(String.Empty));
    Assert.Throws<InvalidOperationException>(() => action(" "));
}

用法:

[Test]
public void Test1()
{
    var controller = new FooController();
    AssertThrowsNullReferenceOrInvalidOperation(controller.ActionName);
}

更新:

对返回 ActionResult 的控制器使用 Func&lt;string, ActionResult&gt;。您也可以为此目的创建通用方法。

【讨论】:

    【解决方案2】:

    正如编辑中所说,控制器有一个返回类型。因此,我不得不从 Action 更改为 Func,并且由于我在单元测试中使用了它,我必须创建一个临时对象来保存该函数。

    根据lazyberezovsky 的回答,这是我生成的代码:

        public class BaseClass
        {
                protected Func<string, ActionResult> tempFunction;
                public virtual void AssertThrowsNullReferenceOrInvalidOperation()
                {
                    if (tempFunction != null)
                    {
                        Assert.Throws<NullReferenceException>(() => tempFunction(null));
                        Assert.Throws<InvalidOperationException>(() => tempFunction(string.Empty));
                        Assert.Throws<InvalidOperationException>(() => tempFunction(" "));
                    }
                }
        }
    

    那么单元测试是:

    [TestFixture]
    public class TestClass
    {
            [Test]
            public override void AssertThrowsNullReferenceOrInvalidOperation()
            {
                tempFunction = Controller.TestMethod;
                base.AssertThrowsNullReferenceOrInvalidOperation();
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多