2009-07-30 45 views
6

我有一個設置屬性犀牛製品斷言的屬性設置調用了正確的對象類型

public void SetNetworkCredential(string userName, string password, string domain) 
{ 
    _reportExecutionService.Credentials = new NetworkCredential(userName, password, domain); 
} 

我如何驗證證書被稱爲具有有效的NetworkCredential的方法?

我想這TestMethod的,但沒有成功,因爲的NetworkCredential對象是不同的引用

[TestMethod] 
public void TestTest() 
{ 
    const string userName = "userName"; 
    const string password = "password"; 
    const string domain = "domain"; 

    var mock = MockRepository.GenerateMock<IReportExecutionService>(); 
    var rptService= new ReportService(mock); 

    rptService.SetNetworkCredential(userName, password, domain); 

    mock.AssertWasCalled(x => x.Credentials = new System.Net.NetworkCredential(userName, password, domain)); 
} 

有沒有辦法來驗證的setter被稱爲與類型的NetworkCredential的對象,並用正確的參數?

回答

15

我通過使ReportService的接受網絡憑證而不是用戶名,密碼固定它,域

public void SetNetworkCredential(NetworkCredential networkCredential) 
{ 
    _reportExecutionService.Credentials = networkCredential; 
} 

所以我的測試是非常容易

[TestMethod] 
public void TestTest() 
{ 
    const string userName = "userName"; 
    const string password = "password"; 
    const string domain = "domain"; 

    var mock = MockRepository.GenerateMock<IReportExecutionService>(); 
    var rptService= new ReportService(mock); 

    var networkCredential = new System.Net.NetworkCredential(userName, password, domain); 

    rptService.SetNetworkCredential(networkCredential); 

    mock.AssertWasCalled(x => x.Credentials = networkCredential); 
} 
+0

優秀的答案,所以這個代碼實際工作它測試,如果制定者與給定值稱爲: mock.AssertWasCalled(X => x.PropertyName = VALUE_WE_ARE_CHECKING); – Roboblob 2010-02-18 09:06:50

3

編輯:反思這個問題,我以前建議的回答或許根本無法工作。這裏的原因:

本質上講,你正試圖驗證依賴的依賴已正確設置。這可能就是爲什麼你爲此編寫單元測試時遇到問題的原因。您可能需要考慮將SetNetworkCredential方法轉換爲實現IReportExecutionService的類是否有意義。

如果你這樣做,這個方法的單元測試是很簡單:

[Test] 
public void TestSetNetworkCredential() 
{ 
    const string userName = "userName"; 
    const string password = "password"; 
    const string domain = "domain"; 

    var rptService= new ReportExecutionService(); 

    rptService.SetNetworkCredential(userName, password, domain); 
    Assert.AreEqual(userName, rptService.Credentials.UserName); 
    Assert.AreEqual(password, rptService.Credentials.Password); 
    Assert.AreEqual(domain, rptService.Credentials.Domain); 
} 
+0

這將是理想的肯定。但是實現IReportExecutionService的類是一個代碼生成類(WSDL到SSRS),我提取了IReportExecutionService,以便我可以嘲笑它。 – 2009-07-31 16:31:40