Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 273
Ask Avatar asked Mar 18 '26 18:03

Ask


1 Answers

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);
like image 148
Karina Avatar answered Mar 21 '26 08:03

Karina