我是单元测试和起订量的新手。我有一个存储库类来检索用户。这是存储库类代码:
public class UserRepository : IUserRepository
{
private readonly UserManager<UserEntity> _userManager;
private readonly IMapper _mapper;
public UserRepository(
UserManager<UserEntity> userManager,
IMapper mapper)
{
_userManager = userManager;
_mapper = mapper;
}
public async Task<IEnumerable<User>> GetUsersAsync(
PagingOptions pagingOptions)
{
IQueryable<UserEntity> query = _userManager.Users;
// query = searchOptions.Apply(query);
// query = sortOptions.Apply(query);
var size = await query.CountAsync();
var items = await query
.Skip(pagingOptions.Offset.Value)
.Take(pagingOptions.Limit.Value)
.ProjectTo<User>(_mapper.ConfigurationProvider)
.ToArrayAsync();
return items;
}
}
如下图所示,当我正常运行应用程序时,此方法工作正常。
但是当我使用x单元单元测试项目运行相同的代码时,执行var size = await query.CountAsync();
时出现以下错误:
IQueryable源的提供程序未实现 IAsyncQueryProvider。仅实现IAsyncQueryProvider的提供程序 可以用于Entity Framework异步操作。
这是我的单元测试代码:
public class UserRepositoryTests
{
[Fact]
public async void GetUsers_AtleastOne_ReturnOneOrMore()
{
// Arrange
var connectionStringBuilder =
new SqliteConnectionStringBuilder { DataSource = ":memory:" };
var connection = new SqliteConnection(connectionStringBuilder.ToString());
var options = new DbContextOptionsBuilder<GallaContext>()
.UseSqlite(connection)
.Options;
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
var mockUserManager = new Mock<UserManager<UserEntity>>(new Mock<IUserStore<UserEntity>>().Object,
new Mock<IOptions<IdentityOptions>>().Object,
new Mock<IPasswordHasher<UserEntity>>().Object,
new IUserValidator<UserEntity>[0],
new IPasswordValidator<UserEntity>[0],
new Mock<ILookupNormalizer>().Object,
new Mock<IdentityErrorDescriber>().Object,
new Mock<IServiceProvider>().Object,
new Mock<ILogger<UserManager<UserEntity>>>().Object);
var autoMapper = new MapperConfiguration(mc => mc.AddProfile(new MappingProfile())).CreateMapper();
var pagingOptions = new PagingOptions
{
Limit = 25,
Offset = 0
};
using (var context = new GallaContext(options, mockHttpContextAccessor.Object))
{
context.Database.OpenConnection();
context.Database.EnsureCreated();
var userRepository = new UserRepository(mockUserManager.Object, autoMapper);
// Act
var users = await userRepository.GetUsersAsync(pagingOptions);
// Assert
users.Should().HaveCountGreaterOrEqualTo(1);
}
}
}
我错误地嘲笑 UserManager
吗?我的上下文类还具有要通过OnModelCreating
方法添加到数据库中的数据。因此,在单元测试中调用context.Database.EnsureCreated();
时上下文具有数据。这是运行单元测试时错误图像的屏幕截图
谢谢
阿卜杜勒