C# Windows注册表操作的单元测试

C# Windows注册表操作的单元测试,c#,C#,我想模拟windows注册表,我需要在使用C#的单元测试中使用它。 我已经编写了为HKLM和HKCU设置注册表的函数。如何为下面的函数编写单元测试。我不想使用systemWrapper 请问有谁能帮忙吗 public static bool createHkcuRegistry(string registryPath, string valueName, string value, RegistryValueKind valueKind = RegistryValueKind.String)

我想模拟windows注册表,我需要在使用C#的单元测试中使用它。 我已经编写了为HKLM和HKCU设置注册表的函数。如何为下面的函数编写单元测试。我不想使用systemWrapper 请问有谁能帮忙吗

  public static bool createHkcuRegistry(string registryPath, string valueName, string value, RegistryValueKind valueKind = RegistryValueKind.String)
    {
        try
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(registryPath, true);
            if (key != null)
            {
                key.SetValue(valueName, value, valueKind);
                key.Close();

            }
            else
            {
                RegistryKey newKey = Registry.CurrentUser.CreateSubKey(registryPath);
                newKey.SetValue(valueName, value, valueKind);
            }
            return true;
        }        
      }

若您希望它真正模拟,那个么可以通过接口将它的依赖关系注入任何使用者。比如:

public interface IRegistryService
{
  bool CreateHkcuRegistry(string registryPath, string valueName, string value, RegistryValueKind valueKind = RegistryValueKind.String);
}

public class RegistryService : IRegistryService
{
  public bool CreateHkcuRegistry(string registryPath, string valueName, string value, RegistryValueKind valueKind = RegistryValueKind.String)
  {
    try
    {
      RegistryKey key = Registry.CurrentUser.OpenSubKey(registryPath, true);
      if (key != null)
      {
         key.SetValue(valueName, value, valueKind);
         key.Close();
      }
      else
      {
         RegistryKey newKey = Registry.CurrentUser.CreateSubKey(registryPath);
                    newKey.SetValue(valueName, value, valueKind);
      }
      return true;
    }        
  }
}
用法示例:

public class ConsumerSample
{
   privare IRegistryService _registryService;

   public ConsumerSample(IRegistryService registryService)
   {
      _registryService = registryService;
   }

   public void DoStuffAndUseRegistry()
   {
       // stuff
       // now let's save
       _registryService.CreateHkcuRegistry("test","testValue","mytest");
   } 
}


var consumer = new ConsumerSample(new RegistryService());

然后在需要的地方使用真正的实现,并在需要的地方在测试中模拟它。

我在维护的开源库中遇到了同样的挑战。这里有一个完整的注册表实现,支持模拟和测试:


用法如Vidas的回答所述。

为什么不使用
systemWrapper
?既然您不想使用systemWrapper,那么您可以自己重新创建抽象,因为解决此问题的最佳途径是通过抽象注册表访问。我需要模拟实际的注册表,我该怎么做?在单元测试上述功能时,它不应该触碰系统注册表。。。所以我需要模拟这个系统registry@VJL然后,您需要创建
IRegistryService
的模拟并使用它。模拟系统注册表是一种自己动手的方法。抽象出你想要的功能,然后模仿它。如果我模仿,那么单元测试就没有用了IRegistryService@VJL,你的回答令人困惑。我们可能互相误解了。您说它不应该触碰系统注册表。这是正确的。这就是为什么我们模拟了一个模拟单元测试实际注册表的服务。如果您实际触摸系统注册表,则它不再是单元测试,而是更改为集成测试。您希望在不实际接触系统注册表的情况下对功能进行单元测试。然后模拟您想要的功能。这就是我试图解释的,也是上面的答案试图解释的。我们彼此了解吗?不,还是我弄错了?我需要模拟实际的注册表。我该怎么做?