最小起订量的单元测试通用方法

本文关键字:单元测试 方法 | 更新日期: 2023-09-27 17:53:12

我有一个通用的方法,从表返回记录列表:

public List<T> GetValidRecords<T>() where T: class, IGetListOfTables
{
    try
    {
        return _context.Set<T>().Where(x => x.Valid == 1).ToList();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

,我对这个方法有一个单元测试:

[TestMethod]
public void GetValidRecords()
{
    var data = new List<tableName>
    {
        new tableName() {Valid= 1},
        new tableName() {Valid= 1}
    }.AsQueryable();
    var mockSet = new Mock<DbSet<tableName>>();
    mockSet.As<IQueryable<tableName>>().Setup(m => m.Provider).Returns(data.Provider);
    mockSet.As<IQueryable<tableName>>().Setup(m => m.Expression).Returns(data.Expression);
    mockSet.As<IQueryable<tableName>>().Setup(m => m.ElementType).Returns(data.ElementType);
    mockSet.As<IQueryable<tableName>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
    var mockContext = new Mock<ALMONEntitiesNew>();
    mockContext.Setup(x => x.tableName).Returns(mockSet.Object);
    var database = new Database(mockContext.Object);
    var numberOfRecords = database.GetValidRecords<tableName>();
    Assert.AreEqual(2, numberOfRecords.Count, "Wrong number of valid records.");
}

问题是我从表中得到实际的记录数,而不是moqed数。我该怎么修理它?

最小起订量的单元测试通用方法

您需要从GetValidRecords方法中获取EF实现的所有依赖,特别是_context,否则EF特定的实现将不断地渗入您的单元测试中。为了测试GetValidRecords作为一个单元,你需要使它能够独立存在。如果你想测试它,因为它是我建议使用集成测试,这实际上是从数据库检索记录,并断言他们回来的OK -这将不需要使用任何mock框架,是一个完美的方式来测试这个功能。

关于使GetValidRecords独立的主题,我看到DbSet实现了IEnumerable,所以也许你想要的是这样的东西:

public static List<T> GetValidRecords<T>(this IEnumerable<T> source) where T: class, IGetListOfTables
{
    if (null == source)
    {
        throw new ArgumentNullException("source");
    }
    return source.Where(x => x.Valid == 1).ToList();
}