我有一个单元测试,我测试了我的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的新手,所以我没有想到,但我会这么做。如果您想添加该答案作为答案,我会将其标记为正确的答案。 –