CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Faking ObjectQuery<T> using TypeMock

478 Views
Copy Code Show/Hide Line Numbers
//Class Under Test
public class CategoryRepository : BaseRepository<Category>
{
    //EntityContainer is an ObjectContext
    public CategoryRepository(EntityContainer context)
        : base(context){}
 
    //Method Under Test
    public Category FindById(Guid id)
    {
       //DataContext is a propery under base class will return the EntityContainer
       return DataContext.Categories.FirstOrDefault(c => c.Id == id);
    }
}
 
//Test Class
[Isolated]
public class CategoryRepositoryFixture
{
    private readonly EntityContainer _context;
    public CategoryRepositoryFixture()
    {
       _context = Isolate.Fake.Instance<EntityContainer>();
       Isolate.Fake.StaticMethods<UniqueNameGenerator>(Members.ReturnRecursiveFakes);
    }
 
    [Fact]
    public void FindById_Should_Return_Correct_Category()
    {
        //_context is a fake ObjectContext instance.
        var repository = new CategoryRepository(_context);
        
        //In memory collection store of categories
        List<Category> inMemoryCategories = CreateCategoriesList();
        
        Guid id = categories[0].Id;
 
        //Fake ObjectQuery<Category>
        //Must call AsQueryable() extension in order for this to work
        Isolate.WhenCalled(() => _context.Categories)
               .WillReturnCollectionValuesOf(inMemoryCategories.AsQueryable());
        
        //Act
        Category found = repository.FindById(id);
 
        //Assert
        Assert.Equal(id, found.Id);
    }
}
by Muhammad Mosa
  September 02, 2009 @ 10:58am
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate