2014-05-22 17 views
0

當我從ConsoleApp調用它時,以下方法在我的類庫中工作正常。但是當我嘗試單元測試時,註冊表值不會更新。爲什麼?類庫註冊表更新方法從控制檯工作,但不是從單元測試中工作

我得到一個空引用錯誤。

namespace ClassLibrary1 
{ 
    public class Class1 
    { 
     public static void MyMethod() 
     { 
      string targketKey = @"SOFTWARE\MyApp1"; 

      using (Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(targetKey, true)) 
      { 
       rk.SetValue("target", "new value", Microsoft.Win32.RegistryValueKind.String); 
      } 
     } 
    } 
} 
+0

也許與啓動Console應用程序和Visual Studio之間憑據的區別? – HuorSwords

+0

你能幫我理解你爲什麼要比較Visual Studio和Console。您在Visual Studio中創建控制檯應用程序。我爲我的無知道歉。 – Rod

+0

我不會比較這兩個應用程序,只有憑據與您運行每個應用程序。如果您正在Windows 7或Windows 8.x上開發,請嘗試以管理員身份執行Visual Studio並啓動您的單元測試。 – HuorSwords

回答

1

對代碼進行了一些測試後,我認爲我發現了你的問題。請嘗試以下操作:

  • 確保已創建HKLM\SOFTWARE\MyApp1密鑰。
  • 任何CPU更改類項目的目標平臺
  • 保持您的測試項目的目標平臺爲任何CPU
  • 設置測試的默認架構的x64菜單

測試>測試設置>默認處理器架構> 64

  • 檢查這個代碼。

public static void MyMethod() 
{ 
    var rootKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", true); 
    using (var existingKey = rootKey.OpenSubKey("MyApp1", true)) 
    { 
     existingKey.SetValue("target", "double new"); 
     existingKey.Close(); 
    }  

    rootKey.Close(); 
} 

我不明白爲什麼,但如果你想直接初始化existingKey(不rootKey),那麼它的值是null

+0

當我將我的目標平臺更改爲x64時,測試在測試瀏覽器中消失。 – Rod

+0

@羅德,你是對的。請查看我的回答:我更新了它,告訴你如何避免這個問題。 – HuorSwords

+0

謝謝!那工作。順便說一句,有沒有辦法運行此代碼,而不必以管理員身份運行VS?我開始關注代碼訪問安全性,但沒有任何運氣。 – Rod

相關問題