“短路"Moq 的无效方法?

时间:2023-05-07
本文介绍了“短路"Moq 的无效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的团队最近决定使用 Moq 作为我们的模拟框架,因为它具有极大的灵活性和高度可读的语法.由于我们是新手,所以我在看似简单的问题上绊倒了——搜索(这里,谷歌等)发现很多关于起订量其他细微差别的讨论,但不一定是我所追求的,并且几个看似相关的问题变成了红鲱鱼.

my team has made the decision recently to use Moq as our mocking framework for its tremendous flexibility and highly readable syntax. As we're new to it, I'm stumbling on what appears to be simple questions--searches (here, Google, etc.) find plenty of discussions on other nuances of Moq, but not necessarily what I'm after, and the few seemingly related questions have turned into red herrings.

我们正在测试一个具有外部依赖项的类(准确地说是 Amazon SimpleDb),但不希望我们的测试绑定到实时连接.一种特殊的方法:

We're testing a class that has an external dependency (Amazon SimpleDb to be precise) but don't want our tests bound to having a live connection out. A particular method:

  • 应用一些业务"逻辑
  • 如果合适,通过我们构建的提供程序调用对 SDB 的调用,我们称之为 SaveItem()

我想对此进行单元测试,以便我们设置所需的上下文并确保 SaveItem() 被调用,但以 SaveItem() 真正不被调用的方式t 被调用(因为 A)SDB 的提供者是一个模拟,它没有完全水合,可能会爆炸,B)我不想为该交易支付数百次和数千次).

I want to unit test this such that we setup the context required and insure that SaveItem() was invoked, but in a manner that SaveItem() really isn't invoked (because A) the provider to SDB is a mock that isn't fully hydrated and will likely bomb and B) I don't want to have to pay for that transaction hundreds and thousands of times).

在处理返回值的方法时,这是微不足道的.

When dealing with methods that returned a value, this was trivial.

mockDb.Setup(d => d.GiveMeSomething()).Returns("Foo");

在我上面概述的情况下,我的SaveItem()"方法是无效的,因此使用 Moq 的 Returns() 方法的选项不可用.虽然我可以设置一个回调来验证 SaveItem() 是否被调用,但我似乎无法让它实际上不做任何事情.

In the case that I outline above though, my "SaveItem()" method is void and therefore the option to use Moq's Returns() method isn't available. And while I can setup a callback to verify SaveItem() is invoked, I can't however seem to get it to not actually do anything.

天真/充满希望,我认为以下方法可行,但似乎仍会调用该方法:

Naive/hopeful, I thought the following would work, but it appears to still invoke the method:

mockDb.Setup(d => d.SaveItem(It.IsAny<object>()));

那么百万美元的问题:以下虚构代码的起订量是多少?

So the million dollar question: What's the Moq of the following fictitious code?

mockDb.Setup(d => d.SaveItem(It.IsAny<object>())).STOP_RIGHT_HERE();

推荐答案

如果 SaveItem() 方法是虚拟的或抽象的,并且你没有设置 Callbase = true,则该方法应重新实现,以使 mock 不做任何事情.

If the SaveItem() method is virtual or abstract, and you're not setting Callbase = true, then the method should be re-implemented to do nothing by the mock.

你应该可以做到:

mockDb.Setup(d => d.SaveItem(It.IsAny<object>())).Verifiable();

...  test here ...

mockDb.Verify();

这篇关于“短路"Moq 的无效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在单元测试中模拟 IMemoryCache 下一篇:EF6 模拟派生的 DbSet

相关文章

最新文章