MOQ - 如何验证静态类调用和委托?

时间:2011-01-27 19:41:39

标签: c# c#-4.0 moq

我刚刚开始阅读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);
    }
}

2 个答案:

答案 0 :(得分:4)

  • 您无法验证静态方法,因为它们不能被Moq嘲笑。
  • 为了验证对代理的调用,创建它们以便它们调用本地函数并保持状态并验证:

    string localString = string.Empty;

    Action<string> action = (string s) => localString = s;

    // ... pass it to the test

    Assert.(localString == "TheStringItMustbe");

(UPDATE)

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

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

答案 1 :(得分:1)

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

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