简体   繁体   English

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

[英]unit testing generic method with moq

I have a generic method which returns list of records from table: 我有一个通用的方法,它从表中返回记录列表:

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);
    }
}

and I have an unit test for this method: 我对此方法进行了单元测试:

[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.");
}

The problem is that I get actual number of records from table, and not moqed number. 问题是我从表中获取了实际记录数,而不是完整的记录数。 How can I fix it? 我该如何解决?

You need to get all dependencies on EF implementation out of the GetValidRecords method, particularly _context otherwise EF specific implementation is going to constantly bleed into your unit tests. 您需要从GetValidRecords方法中获取对EF实现的所有依赖关系,尤其是_context,否则EF特定的实现将不断渗入您的单元测试中。 In order to test GetValidRecords as a unit you need to make it be able to stand on it's own. 为了将GetValidRecords作为一个单元进行测试,您需要使其能够独立存在。 If you want to test it as it is I suggest using an integration test, which is actually retrieving records from the db and asserting they came back OK - this would not require the use of any mocking framework, and is a perfectly OK way to test this functionality. 如果您想按原样进行测试,我建议您使用集成测试,该测试实际上是从数据库中检索记录并断言它们返回了OK-这不需要使用任何模拟框架,并且是测试的一种完美的方式此功能。

On the topic of making GetValidRecords stand alone, I see that DbSet implements IEnumerable, so maybe what you want is something like this: 关于使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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM