Moqing EF抛出异常

本文关键字:抛出异常 EF Moqing | 更新日期: 2023-09-27 18:06:30

我正试图写一个单元测试,但遇到了一个奇怪的问题

 [TestMethod]
    public void Delete_user_save_via_context()
    {
        var data = new List<admins> 
        { 
            new admins() {id = 1,  login = "test" },
        }.AsQueryable();

        var mockSet = new Mock<DbSet<admins>>(data);
        mockSet.As<IQueryable<admins>>().Setup(x => x.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<admins>>().Setup(x => x.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<admins>>().Setup(x => x.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<admins>>().Setup(x => x.GetEnumerator()).Returns(data.GetEnumerator);
        var mockContext = new Mock<Entities>();
        mockContext.Setup(x => x.admins).Returns(mockSet.Object);  //Here i have Exception

        var userService = new UserService(mockContext.Object);
        userService.Delete("test");
        mockSet.Verify(m => m.Remove(It.IsAny<admins>()),Times.Once);
        mockContext.Verify(m => m.SaveChanges(), Times.Once);
    }

抛出异常:

Castle.DynamicProxy。invalidproxyconstructorargumentexception: Can not类的实例化代理:找不到一个构造函数匹配给定参数:System.Linq.EnumerableQuery '

有人能帮我一下吗?

管理类的实现:

public partial class admins
{
    public int id { get; set; }
    public string login { get; set; }   
}

Moqing EF抛出异常

var mockSet = new Mock<DbSet<admins>>(data);

应该是:

var mockSet = new Mock<DbSet<admins>>();