英文:
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.
I want to control the return value of registry.
I tried to use the following for Stub.
RegistryKey registry = MockRepository.GenerateMock<RegistryKey>();
registry.Stub(x => x.GetValue(keyName)).Return("123").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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论