I am having a fair few issues when it comes to Unit Testing my controllers.
I have a UnitOfWork setup in the following way;
IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
IGenericRepository<Model.StockItem> StockItemRepository { get; }
}
UnitOfWork.cs
public class UnitOfWork : IUnitOfWork, IDisposable
{
private DBContext dbContext;
private DbContextTransaction dbContextTransaction;
private GenericRepository<StockItem> mStockItemRepository;
}
public IGenericRepository<StockItem> StockItemRepository
{
get
{
if (mStockItemRepository== null)
{
mStockItemRepository= new GenericRepository<StockItem>(dbContext);
}
return mStockItemRepository;
}
}
I've set-up a base controller that all controllers will Inherit.
public abstract class MyBaseController : Controller
{
protected readonly Repository.IUnitOfWork _unitOfWork;
protected MyBaseController ()
{
_unitOfWork = new Repository.UnitOfWork();
}
protected MyBaseController (Repository.IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
}
Example from my controller - The UnitOfWork is passed into the Business Layer constructor, which allows me to query:
[AccessFilter]
[ClientCacheActionFilter]
public ActionResult Details(Int32? ID = null)
{
try
{
if (ID.HasValue)
{
using (Business.ApplicationSettings objApplicationSettings = new Business.ApplicationSettings(_unitOfWork))
using (Business.StockItems StockItems= new Business.StockItems (_unitOfWork))
{
StockItem stockItem = objClients.GetStockItemById(ID.Value);
if (client == null)
{
return HttpNotFound();
}
StockViewmodel = new StockViewmodel (stockItem);
var funded = objApplicationSettings.GetApplicationSettingValue("funded");
if (funded == "1")
{
model.showFunded = true;
}
return View(model);
}
}
else
{
return RedirectToAction("Index");
}
}
catch (Exception exc)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(exc);
return RedirectToAction("Index");
}
}
My problem is when I am of course unit Testing my controller methods, they will be calling into the DB via UnitOfWork, and also not being able to access cached values etc. As you can see in the controller above, it will break on the Cached settings due to Cache being null(called by objApplicationSettings.GetApplicationSettingValue) and I'm unsure if the UnitOfWork should be used in this way as it's calling into the db when UnitTesting (Using MoQ i'm unable to pass in a mocked unitOfWork).
Aucun commentaire:
Enregistrer un commentaire