Mocking EF core dbcontext and dbset

前端 未结 4 2093
无人共我
无人共我 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:15

    This is a development of R.Titovs answer done in ASP.NET Core 3.1:

    Constructing the Moq (generic method)

    The data is cloned to allow for tests to run in parallel and prevent a test to access data changed by another.

    public static Mock> SetDbSetData(this Mock dbMock,
            IList list, bool clone = true) 
        where TEnt : class
    {
        var clonedList = clone ? list.DeepClone().ToList() : list.ToList();
        var mockDbSet = clonedList.AsQueryable().BuildMockDbSet();
    
        dbMock.Setup(m => m.Set()).Returns(mockDbSet.Object);
        dbMock.Setup(m => m.ReadSet()).Returns(mockDbSet.Object.AsQueryable());
    
        return mockDbSet;
    }
    

    Using some test data

    _appUserDbSetMock = _dbMock.SetDbSetData(ApplicationUserTestData.ApplicationUserData);
    

    Example test

    [Fact]
    private async Task Handle_ShouldAddANewUser()
    {
        var command = new CreateApplicationUserCommand
        {
            // ...
        };
    
        await _handler.Handle(command, default);
    
        _appUserDbSetMock.Verify(m => m.AddAsync(It.IsAny(), default), Times.Once);
    }
    

    One advantage of using MoqQueryable is that there is no need for a generic repository since DbSet acts like one and the mocking is very easy.

提交回复
热议问题