2012-11-29 27 views
2

是否可以在.NET中將系統時間設置爲正確的服務器時間?我有一個與系統時間混淆的測試用例,我想在測試用例的拆解中恢復它。 是否有可能以編程方式恢復正確的時間(例如從服務器)?在.NET中以編程方式將系統時間設置爲正確的服務器時間?

注:我將需要這個單元測試和驗收測試。注入假時間不適用於後者。

+2

隨着時間的推移在單元測試中處理的清潔方法是講到這裏:http://ayende.com/blog/3408/dealing-with-time-in-tests – ilivewithian

+1

這可能是更容易,更安全抽象概念的時間在你的代碼中,然後在你的單元測試中使用一個存根來提供你需要的任何時間。例如。 '接口ITimeSource {DateTime Now {get; }}。 –

+0

@MartinLiversage我也需要做驗收測試,我仍然需要操作系統時間。 –

回答

0
void setDate(string dateInYourSystemFormat) 
    { 
     var proc = new System.Diagnostics.ProcessStartInfo(); 
     proc.UseShellExecute = true; 
     proc.WorkingDirectory = @"C:\Windows\System32"; 
     proc.CreateNoWindow = true; 
     proc.FileName = @"C:\Windows\System32\cmd.exe"; 
     proc.Verb = "runas"; 
     proc.Arguments = "/C date " + dateInYourSystemFormat; 
     try 
     { 
      System.Diagnostics.Process.Start(proc); 
     } 
     catch 
     { 
      MessageBox.Show("Error to change time of your system"); 
      Application.ExitThread(); 
     } 
    } 
void setTime(string timeInYourSystemFormat) 
    { 
     var proc = new System.Diagnostics.ProcessStartInfo(); 
     proc.UseShellExecute = true; 
     proc.WorkingDirectory = @"C:\Windows\System32"; 
     proc.CreateNoWindow = true; 
     proc.FileName = @"C:\Windows\System32\cmd.exe"; 
     proc.Verb = "runas"; 
     proc.Arguments = "/C time " + timeInYourSystemFormat; 
     try 
     { 
      System.Diagnostics.Process.Start(proc); 
     } 
     catch 
     { 
      MessageBox.Show("Error to change time of your system"); 
      Application.ExitThread(); 
     } 
    } 
相關問題