??????????Moq??????????????IUnitOfWork??mock??????????????м??????
????????????
????Application?????BlogCategoryService???????????£?
public class BlogCategoryService : IBlogCategoryService
{
private IBlogCategoryRepository _blogCategoryRepository;
public BlogCategoryServiceImp(IBlogCategoryRepository blogCategoryRepository)
{
_blogCategoryRepository = blogCategoryRepository;
}
public async Task<IList<BlogCategory>> GetCategoriesAsync(int blogId)
{
return await _blogCategoryRepository.GetCategories(blogId).ToListAsync();
}
}
?????????????Entity Framework??System.Data.Entity????????μ?ToListAsync()?????????
????Repository??BlogCategoryRepository???????????£?
public class BlogCategoryRepository : IBlogCategoryRepository
{
private IQueryable<BlogCategory> _categories;
public BlogCategoryRepository(IUnitOfWork unitOfWork)
{
_categories = unitOfWork.Set<BlogCategory>();
}
public IQueryable<BlogCategory> GetCategories(int blogId)
{
return _categories.Where(c => c.BlogId == blogId);
}
}
??????????BlogCategoryRepository??????????????IUnitOfWork??????BlogCategory?????????
??????????????????????????Moq??IUnitOfWork??????mock??——??IUnitOfWork.Set()??????????IQueryable?????BlogCategory????????????£?
[Fact]
public async Task GetCategoriesTest()
{
var blogCategories = new List<BlogCategory>()
{
new BlogCategory {  BlogId = 1?? Active = true?? CategoryId = 1?? Title = "C#" }??
new BlogCategory {  BlogId = 1?? Active = false?? CategoryId = 2?? Title = "ASP.NET Core" }
}.AsQueryable();
var mockUnitOfWork = new Mock<IUnitOfWork>();
mockUnitOfWork.Setup(u => u.Set<BlogCategory>()).Returns(blogCategories);
_categoryService = new BlogCategoryServiceImp(new BlogCategoryRepository(mockUnitOfWork.Object));
var actual = await _categoryService.GetCategoriesAsync(1);
Assert.Equal(2?? actual.Count());
actual.ToList().ForEach(c => Assert.Equal(1?? c.BlogId));
}
????????????
???????е??????????????????????
????The source IQueryable doesn't implement IDbAsyncEnumerable<BlogCategory>.
????Only sources that implement IDbAsyncEnumerable can be used for Entity Framework asynchronous operations.
???????????????????????BlogCategoryService???????EF??ToListAsync()????????????????????????????IDbAsyncEnumerable???????????List?????????IQueryable???????????????????????????????????????IDbAsyncEnumerable????????????????EF????????????????????????????????DbSet??????mock??DbSet????????ж???