MOQ - check a method is called with only specific parameters

微笑、不失礼 提交于 2019-12-03 21:31:25

You can do this through a strict mock though not strictly AAA (As there is no Assert part, and Loose mocking is more robust) will catch other variations that you don't want.

Just use MockBehavior.Strict on your mock.

public interface IFoo
{
    void Foo(string arg);
}

public class Bar
{
   public void CallFoo(IFoo f)
   {
      f.Foo("hello");
      f.Foo("bar");  // Moq will throw an exception on this call
   }
}

[Test]
public void ss()
{
    var bar = new Bar();

    var foo = new Mock<IFoo>(MockBehavior.Strict);
    foo.Setup(x => x.Foo("hello"));

    bar.CallFoo(foo.Object); //Will fail here because "bar" was not expected 
}

_mockChef.Verify(chef => chef.Bake(It.Is<CakeFlavors>(vetoArgsPredicate), It.IsAny<bool>()), Times.Never());

You can use Argument Constraints aka It.Is<T>(predicate) with a method that evaluates to true for invalid arguments and combine that with a Times.Never().

OR
You could strict mocks as another answer here demonstrates ; but they tend to make your tests brittle. So their use is discouraged unless you absolutely need them.

For more details, See bullet #5 and #9 here

Another possibility is to use a callback storing the parameter in a list or something. Then you can assert at the end that the list looks like you expected. In this manner you can keep the AAA pattern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!