Click here to Skip to main content
15,886,016 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a method that I want to test with moq:
C#
public List<T> GetValidRecords<T>(Entities context) where T: class, IGetListOfTables
{
    try
    {
        return context.Set<T>().Where(x => x.Valid == 1).ToList();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}


I've created unit test:
C#
[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();
    var numberOfRecords = database.GetValidRecords<tableName>(mockContext.Object);
    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?
Posted
Updated 24-Mar-14 23:48pm
v3
Comments
Maarten Kools 25-Mar-14 5:25am    
I may be completely wrong here, but you pass new Entities() to the GetValidRecords method. And in that method, you iterate through the context variable, which is equal to new Entities().
Alexander Dymshyts 25-Mar-14 5:47am    
Yes, you are right, my fault. But it still not solves the Problem. I still get values from db, and not from my moq object

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900