Модульный тест универсального репозитория с использованием NUnit и NSubstitute



Как я могу выполнить модульные тесты, используя NUNit и NSubstitute, я хочу проверить вставку поддельного объекта "GamaItem" и проверить, что он работает, и если SaveChanges был запущен.



Я новичок в модульном тесте, и я не уверен, как я могу подделать объект dbContext.



Заранее благодарю.



Единица работы:



public class UnitOfWork: IUnitOfWork, IDisposable
{
private SRColorContext context = new SRColorContext();
private GenericEntityRepository<HairColorType> hairColorTypeRepository;
private GenericEntityRepository<GamaItem> gamaItemRepository;

public UnitOfWork()
{
if (context == null)
{
context = new SRColorContext();
}
}

public UnitOfWork(SRColorContext context)
{
this.context = context;
}


public GenericEntityRepository<HairColorType> HairColorTypeRepository
{
get
{
if (this.hairColorTypeRepository == null)
{
this.hairColorTypeRepository = new GenericEntityRepository<HairColorType>(context);
}
return hairColorTypeRepository;
}
}

public GenericEntityRepository<GamaItem> GamaItemRepository
{
get
{
if (this.gamaItemRepository == null)
{
this.gamaItemRepository = new GenericEntityRepository<GamaItem>(context);
}
return gamaItemRepository;
}
}

public void Save()
{
context.SaveChanges();
}

private bool disposed = false;


protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}


public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}


Универсальный Репозиторий:



public class GenericEntityRepository<TEntity> where TEntity : class
{
internal SRColorContext context;
internal DbSet<TEntity> dbSet;

public GenericEntityRepository(SRColorContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}

public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity,bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;

if(filter != null)
{
query = query.Where(filter);
}

foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query.Include(includeProperty);
}

if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}

}

public virtual TEntity GetById(object id)
{
return dbSet.Find(id);
}

public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}

public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}

public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}

public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
579   1  

1 ответ:

Я думаю, что вы должны подделать объект контекста, чтобы избежать вызова БД, а не сущности (если вы не можете просто создать его)

В случае, если вы хотите написать модульные тесты для классаUnitOfWork и используете NSubtitute (или любой другой фреймворк .NET OSS Mocking), вы должны использовать инъекцию зависимостей и заменить экземпляр контекста поддельным экземпляром.

Вам также может потребоваться обернуть контекстный класс-если он запечатан или используемые методы не являются виртуальными.

Comments

    Ничего не найдено.