在Moq中使用Match.Create

Mat*_*ias 4 c# moq

使用Match.CreateMoq 时我有一种奇怪的行为.

当我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);
      }
Run Code Online (Sandbox Code Playgroud)

是什么原因?

Mat*_*ias 7

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

public string StringThreeCharsLong ()
{
  return Match.Create<string> (s => s.Length == 3);
}
Run Code Online (Sandbox Code Playgroud)

我认为这很好,因为它降低了单元测试中的噪音.

MyMock.Verify (m => m.Method (StringThreeCharsLong());
Run Code Online (Sandbox Code Playgroud)


k.m*_*k.m 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)));
Run Code Online (Sandbox Code Playgroud)

另外,为了达到相同的效果,但语法稍短,可以将It.Ismatcher与expression参数一起使用:

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)));
Run Code Online (Sandbox Code Playgroud)