Search code examples
c#rhino-mocks

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


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


Solution

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