I would like to unit test an Add method in a repository that returns void. I’m interested in testing the actual adding of elements without hitting the database (not whether Add was called or not). Is this the correct way?
var list = new List<Foo>();
var repo = new Mock<IFooRepository>();
repo.Setup(x => x.Add(It.IsAny<Foo>()))
.Callback((Foo f) =>
{
list.Add(f);
});
repo.Object.Add(new Foo { FooId = 1 });
Assert.IsTrue(list.Any(x => x.FooId == 1));
No, the only thing you’re testing here is Moq itself. You could try mocking the underlying layer, e.g. ISession if you’re using Nhibernate.