使用moq进行单元测试通用方法

时间:2014-03-24 16:13:17

标签: c# unit-testing moq

我有一个泛型方法,它返回表中的记录列表:

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数。 我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要从GetValidRecords方法中获取EF实现的所有依赖项,尤其是_context,否则EF特定的实现将不断渗透到您的单元测试中。为了测试GetValidRecords作为一个单元,你需要让它能够站在它自己的身上。如果你想按原样测试它,我建议使用集成测试,它实际上是从数据库中检索记录并断言它们回来了OK - 这不需要使用任何模拟框架,并且是一种完美的测试方法这个功能。

关于使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();
}
相关问题