因此,FirstOrDefaultAsync()给出了错误:
消息: System.ArgumentNullException:值不能为null。 (参数“ arg0”)
这意味着该值为空。
现在,我得到的数据是IQueryable<Data>
。
我设法使ToListAsync()正常工作。
我只是不明白为什么FirstOrDefaultAsync()没有。 我该如何运作?
我希望两个测试都能正常工作。
这是一个工作代码示例。
namespace Tests.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MockQueryable;
using NSubstitute;
using Xunit;
public class Data
{
public Guid Id { get; set; }
}
public class Service
{
public Service(Repository repository)
{
Repository = repository;
}
public Repository Repository { get; set; }
public virtual async Task<ICollection<Data>> GetAll()
{
return await Repository.GetAll().ToListAsync();
}
public virtual async Task<Data> GetById(Guid id)
{
var data = Repository.GetAll();
return await data.FirstOrDefaultAsync(d => d.Id.Equals(id));
}
}
public class Repository
{
public virtual IQueryable<Data> GetAll()
{
return new TestAsyncEnumerable<Data>(new List<Data> { new Data() { Id = Guid.NewGuid() } }).AsQueryable();
}
}
public class DataTests
{
public DataTests()
{
DataList = new List<Data> { new Data() { Id = GuidId } };
RepositorySubstitute = Substitute.For<Repository>();
ServiceSubstitute = Substitute.For<Service>(RepositorySubstitute);
Service = new Service(RepositorySubstitute);
}
public static Guid GuidId { get; } = Guid.NewGuid();
public ICollection<Data> DataList { get; set; }
public Repository RepositorySubstitute { get; set; }
public Service ServiceSubstitute { get; set; }
public Service Service { get; set; }
public TestAsyncEnumerable<Data> GetTestAsyncEnumerable(ICollection<Data> dataList)
{
return new TestAsyncEnumerable<Data>(dataList.AsQueryable());
}
[Fact]
public async Task GetAllShouldCallGetAllOnRepository()
{
// Arrange
ServiceSubstitute.GetAll().Returns(DataList);
RepositorySubstitute.GetAll().Returns(GetTestAsyncEnumerable(DataList));
// Act
var result = await Service.GetAll();
// Assert
RepositorySubstitute.Received(1).GetAll();
Assert.Single(result);
}
[Fact]
public async Task GetByIdShouldCallGetAllOnRepository()
{
// Arrange
ServiceSubstitute.GetById(GuidId).Returns(DataList.First());
RepositorySubstitute.GetAll().Returns(GetTestAsyncEnumerable(DataList));
// Act
var result = await Service.GetById(GuidId);
// Assert
RepositorySubstitute.Received(1).GetAll();
}
}
}