Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create and populate my mock classes with Autofixture?

Currently I'm using EF6 to implement my repositories inside a UnitOfWork. I also have created an In-Memory mock implementations (MockUnitOfWork & MockRepository) so that I can use them in unit tests, however I now have to deal with the tedious setup of the objects.

Isn't this what Autofixture is designed to do? How would I go about getting a MockUnitOfWork that I can use in my tests that contains Foo and Barr repositories that are populated? I'm using NSubstitute for my mocking framework.

IUnitOfWork

public interface IUnitOfWork
{
    void Save();
    void Commit();
    void Rollback();

    IRepository<Foo> FooRepository { get; }
    IRepository<Bar> BarRepository { get; }
}

IRepository

public interface IRepository<TEntity> where TEntity : class
{
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string         includeProperties = "");

    IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null);
    TEntity GetByID(object id);

    void Insert(TEntity entity);
    void Delete(object id);
    void Delete(TEntity entityToDelete);
    void Update(TEntity entityToUpdate);
}
like image 511
WhiskerBiscuit Avatar asked Mar 12 '14 04:03

WhiskerBiscuit


1 Answers

You're trying to do functional testing here, so it would be wise to have a functional database.

EF can recreate and destroy your database in your setup and teardown methods with a test connection string. This would provide a real functional testing environment for your tests to operate against mimicking the real environment.

Ex:

        [TestFixtureSetUp]
        public static void SetupFixture() //create database
        {
            using (var context = new XEntities())
            {
                context.Setup();
            }
        }

        [TestFixtureTearDown]
        public void TearDown() //drop database
        {
            using (var context = new XEntities())
            {
                context.Database.Delete();
            }
        }

        [SetUp]
        public void Setup() //Clear entities before each test so they are independent
        {
            using (var context = new XEntities())
            {
                foreach (var tableRow in context.Table)
                {
                    context.Table.Remove(tableRow);
                }
                context.SaveChanges();
            }
        }
like image 65
C Bauer Avatar answered Sep 19 '22 07:09

C Bauer