5

Match.Create与 Moq 一起使用时,我有一个奇怪的行为。

当我提取Match.Create为变量时,以下代码片段未通过:

      var mock = new Mock<IA>();
      mock.Object.Method ("muh");
      mock.Verify (m => m.Method (Match.Create<string> (s => s.Length == 3)));

      public interface IA
      {
        void Method (string arg);
      }

是什么原因?

4

3 回答 3

8

谢谢你们俩。但我为此找到了另一个很好的解决方案。如快速入门中所述,您也可以使用方法。首先,我认为无论我使用变量还是方法都没有区别。但显然 Moq 足够聪明。所以表达式和谓词的东西可以转换成:

public string StringThreeCharsLong ()
{
  return Match.Create<string> (s => s.Length == 3);
}

我认为这很棒,因为它减少了单元测试中的噪音。

MyMock.Verify (m => m.Method (StringThreeCharsLong());
于 2013-01-14T21:29:56.050 回答
5

你提取的太多了。谓词就足够了:

var mock = new Mock<IA>();
Predicate<string> isThreeCharsLong = s => s.Length == 3;
mock.Object.Method("muh");
mock.Verify(m => m.Method(Match.Create<string>(isThreeCharsLong)));

或者,为了获得相同的效果但语法稍短,您可以使用It.Ismatcher 和表达式参数:

var mock = new Mock<IA>();
Expression<Func<string, bool>> isThreeCharsLong = s => s.Length == 3;
mock.Object.Method("muh");
mock.Verify(m => m.Method(It.Is<string>(isThreeCharsLong)));
于 2013-01-14T21:17:43.323 回答
4

编辑:再次把你的问题弄错了:

问题是Match.Create<string> (s => s.Length == 3);返回一个字符串。它只能在.Verify()调用内部使用。同样的情况发生在It.Is<string>(Expr),如果你提取一个变量,它将作为一个简单的 System.String 传递,并且 verify 将检查它作为一个值(并且失败,因为该值将只是 String.Empty)

var mock = new Mock<IA>();

//this will be a string, and contain just ""
var yourMatcher = Match.Create<string> (s => s.Length == 3);

mock.Object.Method ("muh");

//this will fail because "muh" != ""
mock.Verify (m => m.Method (yourMatcher));

public interface IA
{
  void Method (string arg);
}
于 2013-01-14T20:22:21.940 回答