Windows注册表操作的单元测试

本文关键字:单元测试 操作 注册表 Windows | 更新日期: 2023-09-27 17:57:41

我想用C#模拟我的单元测试中需要使用的windows注册表。我已经编写了为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;
        }        
      }

Windows注册表操作的单元测试

如果您想让它真正模拟,可以通过接口将它的依赖项注入任何使用者。类似于:

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());

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

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

https://github.com/dwmkerr/dotnet-windows-registry

用法正如Vidas的回答中所描述的那样。