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
This is a development of R.Titovs answer done in ASP.NET Core 3.1:
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;
}
_appUserDbSetMock = _dbMock.SetDbSetData(ApplicationUserTestData.ApplicationUserData);
[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.