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

TypeMock Isolator Live Objects

333 Views
Copy Code Show/Hide Line Numbers
//Class under test code snippet
public class CategoryRepository : BaseRepository<Category>
{
        //EntityContainer class is an ObjectContext of Entity Framework
        public CategoryRepository(EntityContainer context)
            : base(context)
        {
        }
        public override void Add(Category category)
        {
            if (CategoryExists(category.Name))
            {
                throw new ArgumentException("Some error message here...", "entity");
            }
            base.Add(category);
        }
        
        public bool CategoryExists(string categoryName)
        {
            //Context is a property in base class of type EntityContainer 
            //which is an EF ObjectContext
            return Context.Categories.Any(c=>c.Name == categoryName)
        }
}
 
//Test Class
using TypeMock.ArrangeActAssert;
using Xunit;
 
namespace ProjectName.Repository.EntityFramework.Tests
{
    [Isolated]
    public class CategoryRepositoryFixture
    {
        [Fact]
        public void Add_ExistingCategory_ShouldThrowArgumentException()
        {
            //Fun, Easy to fake EF ObjectContext. Wasn't applicable with Moq.
            var context = Isolate.Fake.Instance<EntityContainer>();
 
            //Real instance of CategoryRepository
            var repo = new CategoryRepository(context);
            
            //Live Objects as TypeMock team call this
            //Faking a method call on live none faked instance. 
            //Note that repo is an instance of CategoryRepository
            //And it is not faked.
            Isolate.WhenCalled(() => repo.CategoryExists("Dummy"))
                   .WithExactArguments()
                   .WillReturn(true);
 
            Assert.Throws(typeof(ArgumentException), 
                         () => repo.Add(new Category { Name = "Dummy" }));
        }
    }
}
by Muhammad Mosa
  August 31, 2009 @ 1:55pm
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