如果我在这里有正确的方法,我很难理解。我想测试一个存储库。存储库依赖于 DbContext。我希望能够验证存储库没有在 IDbSet 类型的属性上调用函数 Add,该属性是 DbContext 的成员。
我尝试了两种方法。用行为验证,用状态验证。似乎用行为验证是正确的,因为谁知道存根状态在假对象中做了什么。
public void VerifyBehaviour()
{
// Arrange
var stubEntities = MockRepository.GenerateStub<IWsStatContext>();
var stubManufcturers = MockRepository.GenerateStub<IDbSet<Manufacturer>>();
var manufacturer = new Manufacturer() { Name = "Dummy" };
var manufacturers = new List<Manufacturer>();
manufacturers.Add(manufacturer);
stubManufcturers.Stub(x => x.Local).Return(new System.Collections.ObjectModel.ObservableCollection<Manufacturer>(manufacturers));
stubManufcturers.Stub(x => x.SingleOrDefault(m => m.Name == "Dummy")).Return(manufacturer);
stubEntities.Manufacturers = stubManufcturers;
// Act
var sut = new EquiptmentRepository(stubEntities);
sut.AddManufacturer(manufacturer);
// Assert
stubManufcturers.AssertWasNotCalled(x => x.Add(manufacturer));
}
public void VerifyState()
{
// Arrange
var stubEntities = MockRepository.GenerateStub<IWsStatContext>();
var stubManufacturers = new InMemoryDbSet<Manufacturer>();
var manufacturer = new Manufacturer() { Name = "Dummy" };
stubManufacturers.Add(manufacturer);
stubEntities.Manufacturers = stubManufacturers;
// Act
var sut = new EquiptmentRepository(stubEntities);
sut.AddManufacturer(manufacturer);
// Assert
Assert.AreEqual(stubManufacturers.Count(), 1);
}
验证行为方法因 SingleOrDefault 存根周围的 NullReferenceExceptions 而失败。所以我发现帖子说最好验证状态并使用假的 DbSet。但是检查假对象的状态感觉不对。如果 Add 函数的实现方式与真实的不同(它最初是这样,并且我的测试通过了,即使我的存储库被破坏了)。
有谁知道如何存根 SingleOrDefault 以便我可以检查 Add 是否被调用?我无法检查 Add 是否在非 rhinomocked 存根上调用。
谢谢