【问题标题】:MOQ - How to verify static class call and delegates?MOQ - 如何验证静态类调用和委托?
【发布时间】:2011-01-28 07:37:57
【问题描述】:

我刚开始阅读 Moq 框架并考虑将其应用到我现有的代码中。我可以想出一个测试用例来验证基本的函数调用。但现在坚持将其应用于委托和静态类。

下面是被测系统(SUT)

public class SUT : ISUT
{
   private IInterface1 i1;,
   private IInterface2 i2;

   public SUT(IInterface1 i1, IInterface2 i2)
   { 
      this.i1 = i1;
      this.i2 = i2;
   }

   public void FunctionToTest(Action<string> someDelegate, Action otherDelegate)
   {
       var list = i2.GetList();

       foreach(var r in list)
       {
      i1.SomeFunction(r);

          if(someDelegate != null)
              someDelegate("message");                        

          SomeHelper.LogData(r);
       }   

       if(otherDelegate != null)    
             otherDelegate();
   }
}

我的测试设置如下

[TestFixture]
public class when_list_contains_atleast_one_item
{
   ISUT sut;
   Mock<IInterface1> mockI1;
   Mock<IInterface2> mockI2;

   public SUT_Tester()
   {
       mockI1 = new Mock<IInterface1>();
       mockI2 = new Mock<IInterface2>();
       sut = new SUT(mockI1.Object, mockI2.Object);
   }

   [Test]
   public void it_should_call_somefunction_calldelegates_and_log_data()
   {
       var dummyList = new List<string> { "string1", "string2" };
       mockI2.Setup(m2 => m2.GetList()).Returns(dummyList).Verifiable();

       sut.FunctionToTest(It.IsAny<Action<string>>(), It.IsAny<Action>());   

       // How to verify delegates were raised
       // How to verify SomeHelper.LogData was called                

       mockI1.Verify(m => m.SomeFunction(It.IsAny<string>()), Times.Exactly(2));
       mockI2.Verify();
   }
}

如何验证 someDelegate 和 otherDelegate 是否被提出? SomeHelper 是一个静态类,而 LogData 是一个静态函数。如何验证是否调用了 LogData?

下面是 SomeHelper 类

public static class SomeHelper
{
    static ILogger logger = LoggerManager.GetLogger("Something");
    public static void LogData(string input)
    {
        logger.Info(input);
    }
}

【问题讨论】:

    标签: c# c#-4.0 moq


    【解决方案1】:
    • 您无法验证静态方法,因为 Moq 无法模拟它们。
    • 为了验证对委托的调用,创建它们以便它们调用本地函数并且您保持状态并验证:

      string localString = string.Empty;

      Action&lt;string&gt; action = (string s) =&gt; localString = s;

      // ... pass it to the test

      Assert.(localString == "TheStringItMustbe");

    (更新)

    可以检查没有 in 参数的操作,增加一个局部变量并断言它是否已增加(或类似的东西):

    int localVar = 0;
    Action action = () => localVar++;
    // ... pass it to the test
    Assert.(localVar == 1);
    

    【讨论】:

    • 请原谅我的无知。但是如何验证 Action 委托(不带字符串)?
    • 您好,抱歉,刚回到家。如果你有一个没有参数的动作委托,有一个局部变量并在那里增加它并检查它是否已经增加。请参阅 y 更新中的代码示例。
    【解决方案2】:

    您可能需要考虑更改 IInterface1/2 接口,以便它们将 ILogger 作为参数传入 SomeFunction,或者具有可设置的 ILogger 属性。

    然后您可以将模拟的 ILogger 传递给 SomeFunction。

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      相关资源
      最近更新 更多