将 IQueryable 转换为 DbSet

本文关键字:DbSet 转换 IQueryable | 更新日期: 2023-09-27 18:30:34

我不确定这是否可能,但我正在尝试对使用 DbSet 的存储库进行单元测试。 我认为最简单的解决方案就是制作一个可枚举的,并用它替换 DbSet,这是我的尝试。

我正在使用C#,EntityFramework,XUnit和Moq

[Fact]
public void SomeTest() 
{
    //arrange
    var mockContext = new Mock<MyDbContext>();
    var mockData = new List<Person>
        {
            new Person { Name = "Jim", Age = 47 }
        };
    mockContext.Setup(db => db.Persons).Returns((DbSet<Person>)mockData.AsQueryable());
    var repo = PersonRepository(mockContext.Object); 
    //act
    var result = repo.GetByFirstName("Jim");
    //assert
    //do some assertion
}

抛出的错误是它无法将类型EnumerableQuery转换为mockContext.Returns语句上的DbSet。

下面是类似于界面的外观。

人员存储库.cs

public class PersonRepository: EFRepository<Person>, IPersonRepository
{
    public PersonRepository(DbContext dbContext) : base(dbContext)
    {
    }
    public IQueryable<Link> GetByFirstName(string name)
    {
        return DbSet.Where(p => p.FirstName == name);
    }
}

IPersonRepository.cs

public interface IPersonRepository: IRepository<Person>
{
    IQueryable<Person> GetByFirstName(string name);
}

独立.cs

public interface IRepository<T> where T : class 
{
    IQueryable<T> GetAll();
    T GetById(int id);
    void Add(T entity);
    void Delete(T entity);
    void Delete(int id);
    void Update(T entity);
}

EFRepository.cs

public class EFRepository<T> : IRepository<T> where T : class
{
    protected DbContext DbContext { get; set; }
    public IDbSet<T> DbSet { get; set; }
    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }
    ...
}

将 IQueryable<T> 转换为 DbSet<T>

您可以做的是将 Linq 表达式从存储库移动到业务逻辑中,并改为模拟存储库。

public interface IPersonRepository : IRepository<Person>
{
    IQueryable<Person> GetAll { get; }
}
public class PersonRepository : EFRepository<Person>, IPersonRepository
{
    // ...
    public IQueryable<Person> GetAll
    {
        get { return DbSet; }
    }
}
public class SomeBusinessLogicClass
{
    private readonly IPersonRepository _people;
    public SomeBusinessLogicClass(IPersonRepository people)
    {
        _people = people;
    }
    public IEnumerable<Person> GetByFirstName(string name)
    {
        return _people.GetAll.Where(p => p.FirstName == name);
    }
}

现在重写测试以验证业务逻辑。

[Fact]
public void SomeTest() 
{
    //arrange
    var mockRepository = new Mock<IPersonRepository>();
    var mockData = new List<Person>
        {
            new Person { Name = "Jim", Age = 47 }
        };
    mockRepository.Setup(x => x.GetAll).Returns(mockData);
    var bl = new SomeBusinessLogicClass(mockRepository.Object); 
    //act
    var result = bl.GetByFirstName("Jim");
    //assert
    //do some assertion
}