Ask
Ask

Reputation: 3786

Can not instantiate proxy of class: Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry

I have a method in my repo that calls datacontext.Add method and return resutl.Entity like:

 var result =  _dataContext.Product.Add(product);
 await _dataContext.SaveChangesAsync();
 return result.Entity;

Now I want to create mock for EntityEntry<Product> but I am getting an exception:

Message: Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry`1[[Product, Product.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Could not find a parameterless constructor.

Here is my Test Method code:

 var productMock = new Mock<EntityEntry<Product>>();
 var entity = new Product{Id = 1, Name = "Bag"};
 mappingMock.Setup(m => m.Entity).Returns(entity);
 var dataContextMock = new Mock<DataContext>(_options);
 var productMockSet = new Mock<DbSet<Product>>();
 dataContextMock.Setup(a => a.Product)
     .Returns(productMockSet.Object);
 dataContextMock.Setup(m => m.Product.Add(It.IsAny<Product>())).Returns(productMock.Object);

What am I doing wrong? or is there any other way to Assert EntityEntry?

Upvotes: 3

Views: 4238

Answers (1)

Karina
Karina

Reputation: 91

I think you are missing these mocking objects:

var iStateManager = new Mock<IStateManager>();
var model = new Mock<Model>();

var productEntityEntry = new Mock<EntityEntry<Product>>(
new InternalShadowEntityEntry(iStateManager.Object, new EntityType("Product", model.Object, ConfigurationSource.Convention)));

productEntityEntry.SetupGet(m=> m.Entity).Returns(entity);

Upvotes: 9

Related Questions