Using the test classes from this answer :
How to mock an async repository with Entity Framework Core
The following generic extension method was derived
public static Mock> ToAsyncDbSetMock(this IEnumerable source)
where T : class {
var data = source.AsQueryable();
var mockSet = new Mock>();
mockSet.As>()
.Setup(m => m.GetEnumerator())
.Returns(new TestAsyncEnumerator(data.GetEnumerator()));
mockSet.As>()
.Setup(m => m.Provider)
.Returns(new TestAsyncQueryProvider(data.Provider));
mockSet.As>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As>().Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());
return mockSet;
}
With the above extension method the test can be refactored to
[Fact]
public async Task Can_Paginate() {
//Arrange
var products = GetFakeProducts().ToAsyncDbSetMock();
var productCategories = GetFakeProductCategories().ToAsyncDbSetMock();
var customDbContextMock = new Mock();
customDbContextMock.Setup(x => x.Products).Returns(products.Object);
customDbContextMock.Setup(x => x.ProductCategories).Returns(productCategories.Object);
//...other code removed for brevity
var controller = new ProductsController(customDbContextMock.Object, loggerMock.Object, envMock.Object);
controller.pageSize = 3;
controller.ControllerContext = new ControllerContext(actionContext);
//Act
var result = await controller.List(1, 2);
//Assert
//...other code removed for brevity
}