mercredi 12 décembre 2018

Mocking a Service using Moq in C#

I have a service that is setup in this way.

public Interface IDataService : IDisposable
{
    IQueryable<T> Set<T>() where T : class;

    IDbSet<T> WritableSet<T>() where T : class;
}

IDataService is inherited by DataService.

public abstract class DataService : IDataService
{
    public IDataContext DataContext { get; private set; }

    public IQueryable<T> Set<T>() where T : class
    {
        return DataContext.Set<T>().AsNoTracking();
    }

    public IDbSet<T> WritableSet<T>() where T : class
    {
        return DataContext.Set<T>();
    }

    public AddResult<T> Add<T>(T obj) where T : class, IPersistentEntity
    {
        if (obj == null)
            return new AddResult<T>() { IsValid = false };
        else
        {
            if (obj.Id == Guid.Empty)
                WritableSet<T>().Add(obj);

            bool success = DataContext.SaveChanges() > 0;

            return new AddResult<T>() { Entity = obj, IsValid = success };
        }
    }
}

And The DataService is inherited by EntityService.

public class EntityService : DataService
{
    public EntityService(IDataContext DataContext) : base(DataContext)
    {
    }

    public void EntityStarted(Guid Id)
    {
        var a = GetWriteableById<Entity>(Id);
        a.Status = 1;
        DataContext.SaveChanges();
    }
}

This EntityService is used in one of my components. EntityService's object is created and passed to the component's constructor.

I'm using Moq to perform some tests on the component and for that, the plan was to mock the EntityService such that the EntityService uses a fake db container with dummy data for database like operations. But, I'm not having the best idea to mock this with minimum amount of new code.

The least appealing idea that I have is to create a fake EntityService class using the interface and have it's own implementation suitable for tests.

Help is appreciated! :)

Aucun commentaire:

Enregistrer un commentaire