Mocking EF core dbcontext and dbset

前端 未结 4 1960
无人共我
无人共我 2020-12-28 13:29

I am using ASP.NET Core 2.2, EF Core and MOQ. When I run the test I am getting this error:

Message: System.NotSupportedException : Invalid setup on a

4条回答
  •  一生所求
    2020-12-28 14:23

    To save your time, try to use my Moq/NSubstitute extension MockQueryable: https://github.com/romantitov/MockQueryable supported all Sync/Async operations

    //1 - create a List with test items
    var users = new List()
    {
     new UserEntity,
     ...
    };
    
    //2 - build mock by extension
    var mock = users.AsQueryable().BuildMock();
    
    //3 - setup the mock as Queryable for Moq
    _userRepository.Setup(x => x.GetQueryable()).Returns(mock.Object);
    
    //3 - setup the mock as Queryable for NSubstitute
    _userRepository.GetQueryable().Returns(mock);
    

    DbSet also supported

    //2 - build mock by extension
    var mock = users.AsQueryable().BuildMockDbSet();
    
    //3 - setup DbSet for Moq
    var userRepository = new TestDbSetRepository(mock.Object);
    
    //3 - setup DbSet for NSubstitute
    var userRepository = new TestDbSetRepository(mock);
    

    Note:

    • AutoMapper supported from 1.0.4 ver
    • DbQuery supported from 1.1.0 ver
    • EF Core 3.0 supported from 3.0.0 ver

提交回复
热议问题