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. In order to test GetValidRecords as a unit you need to make it be able to stand on it's own. 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.

On the topic of making GetValidRecords stand alone, I see that DbSet implements IEnumerable, so maybe what you want is something like this:

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归因
不隶属于 StackOverflow
scroll top