Mock AsNoTracking Entity Framework

Looking at the source code of the AsNoTracking() extension method:

public static IQueryable AsNoTracking(this IQueryable source)
{
    var asDbQuery = source as DbQuery;
    return asDbQuery != null ? asDbQuery.AsNoTracking() : CommonAsNoTracking(source);
}

Since source (your DbSet<Product> you’re trying to mock) is indeed a DbQuery (because DbSet is deriving from DbQuery), it tries to invoke the ‘real’ (non-mocked) AsNoTracking() method which rightfully returns null.

Try to mock the AsNoTracking() method as well:

mockSet.Setup(x => x.AsNoTracking()).Returns(mockSet.Object);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)