lundi 26 janvier 2015

Using Moq and Unit testing with EF6

I have started to use Moq and so far, i think i have worked out how to abstract my interface to another layer to support Mocking the DbContext.


Now my code is running and i hit this line



_context.Entry(updated).Property(e => e.Position).IsModified = false;


Now the entry is null, so i get an error. How can i make Moq happy?


Here is most of my IDataContext



public interface IDataContext
{
IDbSet<Content> Contents { get; set; }
IDbSet<FieldGroup> FieldGroups { get; set; }

#region DbContext public properties

DbChangeTracker ChangeTracker { get; }
DbContextConfiguration Configuration { get; }
Database Database { get; }

#endregion

#region DbContext public methods

IEnumerable<DbEntityValidationResult> GetValidationErrors();
DbEntityEntry Entry(object entity);
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
DbSet<TEntity> Set<TEntity>() where TEntity : class;
DbSet Set(Type entityType);
int SaveChanges();
Task<int> SaveChangesAsync();

#endregion

#region State

bool IsState(object entity, EntityState state);
void SetState(object entity, EntityState state);

#endregion
}


To cope with setting state on an object, i then abstracted the following to methods to my DataContext



public bool IsState(object entity, EntityState state)
{
return this.Entry(entity).State == state;
}


public void SetState(object entity, EntityState state)
{
this.Entry(entity).State = state;
}


But i am not sure how to cope with the Property problem.


Any help much appreciated


1 commentaire:

  1. Other than the DbSets all your IContext interface needs is

    DbSet Set () where T : class;
    DbEntityEntry Entry ( T entity ) where T : class;

    Task SaveChangesAsync ();
    int SaveChanges ();
    void Dispose ();

    RépondreSupprimer