我想模拟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;
}
}
答案 0 :(得分:1)
如果您希望它真正模拟,请通过接口将其依赖性注入任何消费者。类似的东西:
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());
然后在需要的地方使用真实实现,并在需要的测试中进行模拟。
答案 1 :(得分:0)
在我维护的开源库中,我也面临着同样的挑战。注册表的完整实现支持我在此处汇总的模拟和测试:
https://github.com/dwmkerr/dotnet-windows-registry
用法与维达斯的回答中所述相同。