Mocking the Registry - SystemWrapper

牧云@^-^@ 提交于 2019-12-07 18:57:20

I figured it out, I was adding the Stubs dealing with OpenSubKey to the initial keyMock and not the one that was returned by OpenRemoteBaseKey()

Here is the fixed code:

[TestMethod()]
public void GetRegistryKeyTest_Mocked()
{
    IRegistryService target = CreateMockedRegistryService();
    string machineName = "localhost";
    RegistryHive hive = RegistryHive.LocalMachine;
    string path = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
    string valueName = "SystemRoot";
    object defaultValue = @"C:\Windows";


    var keyMock = CreateMockedHKLM();
    var remoteKeyMock = CreateMockedHKLM();
    var subKeyMock = MockRepository.GenerateMock<IRegistryKey>();
    subKeyMock.Stub(x => x.Name).Return(keyMock.Name + @"\" + path);
    subKeyMock.Stub(x => x.GetValueNames()).Return(new string[] { valueName });
    subKeyMock.Stub(x => x.GetValue(valueName)).Return(defaultValue);
    remoteKeyMock.Stub(x => x.OpenSubKey(path)).Return(subKeyMock);
    remoteKeyMock.Stub(x => x.GetValue(valueName)).Return(defaultValue);

    keyMock.Stub(x => x.OpenRemoteBaseKey(hive, machineName)).Return(remoteKeyMock);
    target.ChangeBaseKey(keyMock);

    actual = target.GetRegistryKey(machineName, hive, path, valueName, defaultValue);

    Assert.AreEqual(expected.Results, actual.Results);
    subKeyMock.AssertWasCalled(x => x.GetValue(valueName));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!