Mocking DbSet.AddOrUpdate

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?

+4
2

.

, , MockableDbSetWithExtensions DbSet, , AddOrUpdate.

Entity Framework .

public abstract class MockableDbSetWithExtensions<T> : DbSet<T>
    where T : class
{
    public abstract void AddOrUpdate(params T[] entities);
    public abstract void AddOrUpdate(Expression<Func<T, object>> 
         identifierExpression, params T[] entities);
}

[TestMethod]
public void AddItem_ShouldSucceed()
{
    var myItems = new Mock<MockableDbSetWithExtensions<MyItem>>();

    var context = new Mock<MyContext>();
    context.Setup(e => e.MyItems).Returns(myItems.Object);

    MyItemService service = new MyItemService(context.Object);

    ...
}
+5

Nkosi , AddOrUpdate. :

public class MyDbContext: DbContext 
{
    public virtual DbSet<MyItem> Items {get; set;}

    public virtual AddOrUpdate<T>(T item)
    {
         if(typeof(T) == typeof(MyItem))
         {
             Items.AddOrUpdate(item as MyItem)
         }
    }
}

, :

public class MyItemService
{
   private MyContext context;

   public void AddItem(MyItem item)
   {
      this.context.AddOrUpdate(item);
      this.context.SaveChanges();
   }
}
+2

Source: https://habr.com/ru/post/1676195/


All Articles