开发者

MOQ - check a method is called with only specific parameters

开发者 https://www.devze.com 2023-02-22 19:38 出处:网络
I have a method that assigns some values to a dictionary, and in my Moq test I want to ensure that it is only called with a specific set of parameters (i.e., strings).

I have a method that assigns some values to a dictionary, and in my Moq test I want to ensure that it is only called with a specific set of parameters (i.e., strings).

I've tried a variety of things - Setup开发者_JAVA技巧, SetupSet, VerifySet, etc. They all let me ensure that a method is called with the parameters I want, which is fine. But how do I verify that it wasn't called with anything else? None of the above methods will catch this scenario.

I tried to use It.IsInRange to specify which params were ok, but that only accepts ints so for a dictionary lookup is not much use.

Thanks,

Alex


_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


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 
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消