如何在Rhino.Mocks中使用Stub模拟System函数

huangapple go评论61阅读模式
英文:

How to use the Stub in Rhino.Mocks to simulate System functions

问题

在单元测试中,我经常使用 Stub 来模拟第三方函数。

但我不知道如何 Stub 这样的代码。

插入图片描述

我想要控制 registry 的返回值。

我尝试使用以下代码来进行 Stub。

RegistryKey registry = MockRepository.GenerateMock<RegistryKey>();
registry.Stub(x => x.GetValue(keyName)).Return("123").IgnoreArguments();
var Path = _mock.GetAppRegistryPath(appItem, keyName);

但我发现 registry 的值并不是我设置的值。

英文:

In unit testing, I often use Stub to mock third-party functions.

But I don't know how to Stub a code like this.

enter image description here

I want to control the return value of registry.

I tried to use the following for Stub.

    RegistryKey registry = MockRepository.GenerateMock&lt;RegistryKey&gt;();
    registry.Stub(x =&gt; x.GetValue(keyName)).Return(&quot;123&quot;).IgnoreArguments();
    var Path = _mock.GetAppRegistryPath(appItem, keyName);

But I found that the value of resgistry is not the value I set.

答案1

得分: 0

这不太容易。模拟类很少按照您的意图工作(因为只有虚拟方法可以模拟)。正常的方法是将一切都封装在接口后面,这样您就可以模拟对函数的访问。这可能需要很多额外的工作,具体取决于您需要的系统API的数量和类型。

在这种特定情况下,您很幸运,因为已经有人完成了这项工作。有一个名为DotNetWindowsRegistry的包,它是Microsoft.Win32.Registry包的包装器,并添加了必要的模拟接口。

英文:

It's not so easy. Mocking classes rarely works the way you intend it to (because only virtual methods can be mocked). The normal way is to wrap everything behind interfaces, so you can mock the access to the functions. That may be a lot of extra work, depending on the number and type of system APIs you need.

In this particular case, you are lucky, because somebody else already did the work. There's the package DotNetWindowsRegistry that is a wrapper around the Microsoft.Win32.Registry package and adds the necessary mocking interfaces.

huangapple
  • 本文由 发表于 2023年3月9日 13:53:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75680883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定