2009-11-24 35 views

回答

0

雖然我不知道它是什麼(我不這麼認爲),但您應該認真考慮您的代碼是否可以推廣到與接口對接,而不是依賴當前的WindowsIdentity。

這使得您的代碼變得更加靈活,並且使得單元測試更簡單,因爲您可以將任何IPrincipal實現(例如GenericPrincipal)分配給Thread.CurrentPrincipal。只要記住在每個測試用例之後進行適當的Fixture Teardown。這是我們從測試套件的一個典型的例子:

[TestClass] 
public class AuditServiceTest 
{ 
    private IPrincipal originalPrincipal; 

    public AuditServiceTest() 
    { 
     this.originalPrincipal = Thread.CurrentPrincipal; 
    } 

    [TestCleanup] 
    public void TeardownFixture() 
    { 
     Thread.CurrentPrincipal = this.originalPrincipal; 
    } 

    [TestMethod] 
    public void SomeTest() 
    { 
     Thread.CurrentPrincipal = 
      new GenericPrincipal(
       new GenericIdentity("Jane Doe", null)); 
     // More test code 
    } 
} 

這就是說,存在假冒的「單位」測試可能會被擔保的情況。我在MSTest中看到的這種做法是通過在測試用例中編寫顯式模擬代碼。

+0

嗨,馬克 - 尼斯迴應! 對於我的特殊場景,我正在做一個Intranet站點,我在IE中使用Kerberos身份驗證,並且ASP.Net使用模擬代表用戶代表用戶訪問SQL。所以我不認爲通用原則適用於我的情況。 – 2009-11-25 15:46:03

+0

沒錯 - 這就是爲什麼我把這個小小的警告寫在最後:) – 2009-11-25 16:09:05

0

看起來團隊測試看起來不像這樣。我最終編寫了我的單元測試以模擬用於調用LogonUser Win32 API的用戶using this包裝。

現在我的單元測試,像這樣:

[TestMethod] 
public void Assert_Access_Denied() 
{ 
    bool denied = false; 

    using (new Impersonator("SomeValidUserWithNoAccess", "SomeTestDomain", "SomeTestPassword")) 
    {     
     try 
     { 
      // access some method that performs windows auth 
     } 
     catch (UnauthorizedAccessException exc) 
     { 
      denied = true; 
     } 
    } 

    Assert.IsTrue(denied); 
} 
相關問題