2016-07-20 27 views
1

私は私のユニットテストで使用する必要があるWindowsレジストリを模擬したいC#を使用します。 私はHKLMとHKCUのレジストリを設定する関数を書いています。以下の関数のユニットテストを書くにはどうすればいいですか?私はこのWindowsレジストリ操作のユニットテスト

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; 
     }   
     } 
+1

なぜあなたは 'systemWrapper'を望んでいませんか? –

+0

SystemWrapperを使用したくない場合は、抽象レジストリのアクセスを介して、この要件を解決する最善の方法として抽象化を再作成することができます – Nkosi

+0

私は実際のレジストリを偽装する必要があります。 – VJL

答えて

1

上のいずれかの助けが必要であれば、それは本当にモック、インタフェースを介して任意の消費者への依存性を注入することができますsystemWrapper を使用する必要はありません。以下のような何か:

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

次に、目的の場所を実際の実装を使用し、必要なテストでそれをモック。

+0

上記の関数を単体テストしている間は、システムレジストリに触れてはいけません。システムレジストリをモックする必要があります。 – VJL

+0

@VJL次に、IRegistryServiceのモックを作成して使用する必要があります。システムレジストリを嘲笑することは、自分自身でやりたいことを広げる方法です。あなたが望む機能を抽象化し、それを模擬する。 – Nkosi

+0

IRegistryService – VJL

関連する問題