最小起订量-检查仅使用特定参数调用的方法 [英] MOQ - check a method is called with only specific parameters

查看:54
本文介绍了最小起订量-检查仅使用特定参数调用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个为字典分配一些值的方法,在我的Moq测试中,我想确保仅 用一组特定的参数(即字符串)调用.

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).

我已经尝试了多种方法-Setup,SetupSet,VerifySet等.它们都使我确保使用所需的参数来调用方法,这很好.但是我如何验证它没有被其他东西调用?以上方法都无法解决这种情况.

I've tried a variety of things - Setup, 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.

我尝试使用It.IsInRange来指定哪些参数还可以,但是仅接受整数,因此对于字典查找来说并没有太大用处.

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.

谢谢

亚历克斯

推荐答案

您可以通过严格的模拟(尽管不是严格的AAA)来做到这一点(因为没有Assert部分,而Loose的模拟更强大)将捕获您所遇到的其他变体不想.

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.

只需在您的模拟游戏中使用MockBehavior.Strict.

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 
}

这篇关于最小起订量-检查仅使用特定参数调用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆