給出以下方法我可以測試什麼和如何測試?單元測試幫助
public void DoSomething
{
Get Db record
Update Db the record
Log History in Db
Send an email notification
}
給出以下方法我可以測試什麼和如何測試?單元測試幫助
public void DoSomething
{
Get Db record
Update Db the record
Log History in Db
Send an email notification
}
首先,我同意其他海報,這種方法做得太多。我個人認爲它只做Db的東西,然後讓我的應用程序層記錄操作併發送電子郵件。這就是說,到單元測試這種方法,我會做以下(在C#):
首先,給該方法在這樣的構造存在類:
public MyClass(
IRepository repository,
ILoggingService loggingService,
INotificationClient notificationClient)
...其中IRepository
是一個接口是這樣的:
interface IRepository
{
Db GetDbRecord();
void UpdateDbRecord(Db record);
}
...的ILoggingService
是這樣的:
interface ILoggingService
{
void LogInformation(string information);
}
...和INotificationClient
是這樣的:
interface INotificationClient
{
void SendNotification(Db record);
}
在構造體,分配傳入的參數給私人,只讀字段MyClass
。
接下來,在DoSomething
方法,從IRepository
得到Db
記錄,更新和保存回IRepository
。使用ILoggingService
記錄歷史記錄,然後在INotificationClient
上撥打SendNotification()
。
最後,在您的單元測試中,使用模擬框架(如Moq)來模擬每個接口之一。通過嘲笑的對象成MyClass
一個新的實例,調用DoSomething()
,然後驗證您的嘲笑IRepository
被要求更新Db
對象,你的嘲笑ILoggingService
已要求登錄的消息,你的嘲笑INotificationClient
已要求SendNotification()
。這就是說:
Db record = new Db();
var mockRepository = new Mock<IRepository>();
mockRepository.Setup(r => r.GetDbRecord()).Returns(record);
var mockLoggingService = new Mock<ILoggingService>();
var mockNotificationClient = new Mock<INotificationClient>();
new MyClass(
mockRepository.Object,
mockLoggingService.Object,
mockNotificationClient.Object).DoSomething();
// NUnit syntax:
Assert.That(record["ExpectedUpdatedField"], Is.EqualTo("ExpectedUpdatedValue"));
mockRepository.Verify(r => r.UpdateDbRecord(record), Times.Exactly(1));
mockLoggingService.Verify(ls => ls.LogInformation(It.IsAny<string>()), Times.Exactly(1));
mockNotificationClient.Verify(nc => nc.SendNotification(record), Time.Exactly(1));
運行的系統中,你將注入的MyClass
'依賴正確的實現,然後你共享之間更連貫的對象的責任。
有點囉嗦,但這就是我該怎麼做:)
對於單元測試 - 您沒有「單元」方法。它做了太多事情。爲每個作業提取方法並測試這些方法。
通常,單元測試不包括數據庫更改等,因此您必須查看如何攻擊該部分。它將取決於你使用的框架等。你可以模擬數據庫方法並確認你正在調用它們。不要去看看數據是否添加到數據庫等。這不是單元測試,你會開始意識到,你的測試變得片狀,慢,不能並行等。
有集成測試/分貝測試數據部分並確保回滾您修改的任何數據。還要確保沒有測試依賴於其他測試所做的更改。
你在這方面做得太多了。如果你堅持單一責任原則(S.O.L.I.的一部分)。D)那麼你會發現測試更容易,因爲你一次只測試一件事情。你也會發現你的代碼也更容易維護。 – 2011-05-20 22:39:45
如果你看看SOLID的其餘部分,你還會發現一大堆其他的東西讓單元測試變得更容易。 – 2011-05-20 22:40:32