I follow the instructions here to try to mock mine DbSetand DbContextfor unit testing using Moq.
The service I'm testing is as follows:
public class MyItemService
{
private MyContext context;
public void AddItem(MyItem item)
{
this.context.MyItems.AddOrUpdate(item);
this.context.SaveChanges();
}
}
My unit test is as follows
[TestMethod]
public void AddItem_ShouldSucceed()
{
var myItems = new Mock<DbSet<MyItem>>();
var context = new Mock<MyContext>();
context.Setup(e => e.MyItems).Returns(myItems.Object);
MyItemService service = new MyItemService(context.Object);
service.AddItem(new MyItem
{
Id = "1234"
});
}
When I run the test, I get an exception
System.InvalidOperationException: Unable to call public, instance method AddOrUpdate on derived IDbSet<T> type 'Castle.Proxies.DbSet``1Proxy'. Method not found.
I guess the problem is what AddOrUpdateis the extension method to DbSet. I do have System.Data.Entity.Migrationsincluded in my test .cs file.
I tried to add a line
myItems.Setup(e => e.AddOrUpdate(It.IsAny<MyItem>()));
for my unit test, but then I get an exception
System.NotSupportedException: expression refers to a method that does not belong to the mocked object: e => e.AddOrUpdate (new [] {It.IsAny ()})
, unit test, AddOrUpdate?