Почему не работает FindAsync из EF Core в тесте с NSubstitute?
Хочу сделать тесты для методов репозитория с помощью NUnit и NSubstitute. Всё подготовил и сделал первый тест:
public class Tests
{
private List<BlogEntity> data = null!;
private BlogsRepository repository = null!;
[SetUp]
public void Setup()
{
data = new List<BlogEntity>
{
new() { Id = new Guid("daf362fc-4487-4338-8776-d5bca5bc2632"), Description = "A", Reviews = new List<ReviewEntity>() },
new() { Id = new Guid("40503af9-7569-4015-879e-6f70d0088de1"), Description = "B", Reviews = new List<ReviewEntity>() },
new() { Id = new Guid("3c7ffa34-a234-43dc-ab20-849b211190c2"), Description = "C", Reviews = new List<ReviewEntity>() },
};
var mockContext = Substitute.For<IApplicationContext>();
var queryableData = data.AsQueryable();
var set = Substitute.For<DbSet<BlogEntity>, IQueryable<BlogEntity>>();
((IQueryable<BlogEntity>)set).Provider.Returns(queryableData.Provider);
((IQueryable<BlogEntity>)set).Expression.Returns(queryableData.Expression);
((IQueryable<BlogEntity>)set).ElementType.Returns(queryableData.ElementType);
((IQueryable<BlogEntity>)set).GetEnumerator().Returns(queryableData.GetEnumerator());
mockContext.Blogs.Returns(set);
var config = new MapperConfiguration(cfg => cfg.CreateMap<BlogEntity, Blog>());
var mapper = new Mapper(config);
repository = new BlogsRepository(mockContext, mapper);
}
[Test]
public async Task GetAsync_Test()
{
var model = await repository.GetAsync(data[0].Id);
Assert.That(model?.Id, Is.EqualTo(data[0].Id));
}
}
Но почему-то await repository.GetAsync(data[0].Id);
возвращает null. Вот его реализация:
public async Task<Blog?> GetAsync(Guid id)
{
var t = await context.Blogs.FindAsync(id);
return mapper.Map<Blog>(t);
}
В этом методе работает маппер, но не работает FindAsync
. Можете сказать как это можно поправить? Не совсем понимаю, почему не работает, я ведь добавил mockContext.Blogs.Returns(set);
. Если в отладчике навести курсор на mockContext.Blogs
, то там будут все значения из data
.
Источник: Stack Overflow на русском