unit-testingentity-framework-4mockingtypemock-isolator

Testing : How to create fake object context using TypeMock for EF4 model


I am using EF4 in my application and I want to make test cases for DAL methods, which generally hit the database to get data. I am using the Typemock framework for Mocking. I want to mock database call and only want to test queries. E.g.:

ObjectContext.Where(u => u.code == Code) 

For doing this, I need to make Fake ObjectContext for EF Models and want to fill some fake data in Fake ObjectContext so that we can execute our queries (LINQ) on fake ObjectContext. Kindly suggest how can I can create fake object context(Using TypeMock framework) and fill data in the entities.

For example, I have the following method:

protected IObjectSet<T> CreateObjectSet<T>() where T : EntityBase 
{ 
    return _context.CreateObjectSet<T>(); 
}

And I am creating a test case to mock _context, however _context is null. My test case is:

var fakeInMemoryBlogs = GetUsers();    
var fakeContext = Isolate.Fake.Instance<SecurityEntitiesUOW>(); 
var fakeGenericRepository = Isolate.Fake.Instance<GenericRepository>
    (Members.CallOriginal, ConstructorWillBe.Called, fakeContext); 
Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<SecUser>()) 
    .WillReturnCollectionValuesOf(fakeInMemoryBlogs.AsQueryable());

Solution

  • This has been asked a couple of times before. Did some searching and came up with the following resources:

    Introducing Entity Framework Unit Testing with TypeMock Isolator

    http://mosesofegypt.net/post/Introducing-Entity-Framework-Unit-Testing-with-TypeMock-Isolator.aspx

    Abstract the ObjectContext by using the Repository Pattern

    EF4 - possible to mock ObjectContext for unit testing?

    How to mock ObjectContext or ObjectQuery in Entity Framework?

    How to mock ObjectContext or ObjectQuery<T> in Entity Framework?