I'm having a hard time understanding if I've got the right approach here. I want to test a repository. The repository is dependent on a DbContext. I want to be able to verify that the repository did not call a function Add on a property of type IDbSet which is a member of the DbContext.
I've tried two approaches. Verify with behaviour, and verify with state. Seems that verify with behaviour would be right because who knows what the stubbed state is doing in a fake object.
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);
}
Verify behaviour approach fails with NullReferenceExceptions around the stub of SingleOrDefault. So I find posts saying best to verify state and use a fake DbSet. But it feels wrong to be checking state of a fake object. What if the Add function was implemented differently than the real one (which it was originally and my test was passing even though my repository was broken).
Does anyone know how to stub the SingleOrDefault so I can check Add was called? I can't check Add was called on a non-rhinomocked stub.
Thanks