我有一個單元測試,我測試了我的Service類在各種條件下將數據插入到我的Repository類中的正確位置。 My Repository類有三個「存儲」位置,我的Service類有一個公有的AddData
方法,該方法有條件地將數據添加到存儲庫中的三個存儲區(這是生產中的不同數據庫表集)中的一個存儲區。我的單元測試可以查看服務的存儲庫以確保將數據添加到正確的位置嗎?例如:單元測試跨層邊界
服務類看起來是這樣的:
class MyService
{
private readonly IRepository Repository;
// Add data to a different place in the repository based on the value of the 'someSwitch' parameter
public void AddData(MyDataObject data, int someSwitch)
{
if (someSwitch >= 0 && someSwitch < 10)
{
this.Repository.AddToStorageOne(data);
}
else if (someSwitch >= 10 && someSwitch < 20)
{
this.Repository.AddToStorageTwo(data);
}
else
{
this.Repository.AddToStorageThree(data);
}
}
}
單元測試是這樣的:
[TestClass]
public class MyTests
{
[TestMethod]
private void AddData_SwitchValueOf15_ShouldAddToStorageTwo()
{
// Create the MyService class with an in-memory repository
MockRepository repository = new MockRepository();
MyService service = new MyService
{
Repository = repository
};
MyDataObject myDataObject = new MyDataObject();
// Assign some data to myDataObject
// This should insert myDataObject into StorageTwo
service.AddData(myDataObject, 15);
// Here I want to assert that the data got added to "StorageTwo" in the repository
}
}
現在我想測試數據插入到倉庫的StorageTwo
。當然,這將是容易的,我做這樣的事情
Assert.AreEqual(0, repository.StorageOne.Count);
Assert.AreEqual(1, repository.StorageTwo.Count);
Assert.AreEqual(0, repository.StorageThree.Count);
所以我的問題是,是不是OK了我的單元測試(這是檢驗一個服務方法)尋找到這樣的服務的倉庫?如果這樣做是不好的做法,我應該如何檢查數據是否插入到存儲庫中的正確位置?我的服務等級只有一個公共GetData()
方法,該方法結合了StorageOne
,StorageTwo
和StorageThree
的數據,因此Service類沒有任何可以查看各個存儲的公共方法。
是不是就足夠了檢查你的模擬(一個真實的,有起訂量爲例)正確的庫方法被調用,另一個間沒有「T?如果你超越了你正在測試的課程界限,那麼它不再是一個「單元」測試。 –
是的,謝謝。我是Moq的新手,所以我沒有想到,但我會這麼做。如果您想添加該答案作爲答案,我會將其標記爲正確的答案。 –