C# 如何模拟存储库/工作单元
在我的应用程序中,我通过UnitOfWork将通用存储库连接到控制器。我想对我的应用程序进行单元测试。为此,我需要模拟数据库连接。 你能告诉我该怎么办吗?模拟回购?模拟回购和工作单元?如果有任何代码片段/建议,我将不胜感激。 这是我的回购协议:C# 如何模拟存储库/工作单元,c#,unit-testing,mocking,C#,Unit Testing,Mocking,在我的应用程序中,我通过UnitOfWork将通用存储库连接到控制器。我想对我的应用程序进行单元测试。为此,我需要模拟数据库连接。 你能告诉我该怎么办吗?模拟回购?模拟回购和工作单元?如果有任何代码片段/建议,我将不胜感激。 这是我的回购协议: public class GenericRepository<TEntity> where TEntity : class { internal EquipmentEntities context; internal DbSe
public class GenericRepository<TEntity> where TEntity : class
{
internal EquipmentEntities context;
internal DbSet<TEntity> dbSet;
public GenericRepository(EquipmentEntities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
List<Expression<Func<TEntity, bool>>> filter,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
int? Page=0,
params Expression<Func<TEntity, object>>[] included)
{
IQueryable<TEntity> query = dbSet;
foreach(var z in included)
{
query=query.Include(z);
}
if (orderBy != null)
{
query = orderBy(query);
query = query.Skip((Page.Value - 1) * 30).Take(30);
}
if (filter != null)
{
foreach (var z in filter)
{
query = query.Where(z);
}
}
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;
}
}
公共类通用存储,其中tenty:class
{
内部设备实体环境;
内部数据库集;
公共通用存储库(设备实体上下文)
{
this.context=上下文;
this.dbSet=context.Set();
}
公共虚拟IEnumerable Get(
列表过滤器,
Func orderBy=null,
int?Page=0,
参数表达式[]包括在内)
{
IQueryable query=dbSet;
foreach(包括var z)
{
query=query.Include(z);
}
if(orderBy!=null)
{
query=orderBy(查询);
query=query.Skip((Page.Value-1)*30),取(30);
}
if(过滤器!=null)
{
foreach(过滤器中的变量z)
{
query=query.Where(z);
}
}
返回query.ToList();
}
公共虚拟实体GetByID(对象id)
{
返回dbSet.Find(id);
}
公共虚拟空白插入(TEntity实体)
{
添加(实体);
}
公共虚拟无效删除(对象id)
{
TEntity entityToDelete=dbSet.Find(id);
删除(entityToDelete);
}
公共虚拟无效删除(TEntity entityToDelete)
{
if(context.Entry(entityToDelete.State==EntityState.Detached)
{
数据库集连接(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
公共虚拟无效更新(TEntity entityToUpdate)
{
数据库集附加(实体更新);
context.Entry(entityToUpdate.State=EntityState.Modified;
}
}
和工作单元:
public class UnitOfWork {
private EquipmentEntities context = new EquipmentEntities();
private GenericRepository<Role> RoleRepository;
private GenericRepository<Storage> StorageRepository;
private GenericRepository<Device> DeviceRepository;
private GenericRepository<DeviceInstance> DeviceInstanceRepository;
private GenericRepository<DeviceUsage> DeviceUsageRepository;
private GenericRepository<User> UserRepository;
public GenericRepository<Role> roleRepository
{
get
{
if (this.RoleRepository == null)
{
this.RoleRepository = new GenericRepository<Role>(context);
}
return RoleRepository;
}
}
/*
* redundant code for other controllers
*/
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);
}
}
公共类UnitOfWork{
私有设备实体上下文=新设备实体();
私人通用存储角色存储;
专用通用存储库;
私人通用存储设备;
专用通用存储设备安装库;
私人通用存储设备使用存储设备;
专用通用存储用户存储库;
公共一般存储角色存储
{
得到
{
if(this.RoleRepository==null)
{
this.RoleRepository=新的通用存储(上下文);
}
返回角色还原;
}
}
/*
*其他控制器的冗余代码
*/
公共作废保存()
{
SaveChanges();
}
私有布尔=假;
受保护的虚拟void Dispose(bool disposing)
{
如果(!this.disposed)
{
如果(处置)
{
context.Dispose();
}
}
这是真的;
}
公共空间处置()
{
处置(真实);
总干事(本);
}
}
样本控制器:
public class UserController : Controller
{
//private EquipmentEntities db = new EquipmentEntities();
private UnitOfWork unitOfWork = new UnitOfWork();
// GET: /User/
public ActionResult Index(string Name, string Surname, int? Page, string submit)
{
List<Expression<Func<User, bool>>> where = new List<Expression<Func<User, bool>>>();
if (!string.IsNullOrEmpty(Name))
{
where.Add(w => w.Name.Contains(Name));
}
if (!string.IsNullOrEmpty(Surname))
{
where.Add(w => w.Surname.Contains(Surname));
}
var users = unitOfWork.userRepository.Get(where, null, Page, u => u.Role);
return View(users);
}
// GET: /User/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = unitOfWork.userRepository.GetByID(id.Value);
//User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
// GET: /User/Create
public ActionResult Create()
{
ViewBag.RoleId = new SelectList(unitOfWork.roleRepository.Get(null), "Id", "RoleName");
return View();
}
// POST: /User/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,EmployeeNo,Name,Surname,ContactInfo,RoleId")] User user)
{
if (ModelState.IsValid)
{
unitOfWork.userRepository.Insert(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
ViewBag.RoleId = new SelectList(unitOfWork.roleRepository.Get(null), "Id", "RoleName", user.RoleId);
return View(user);
}
// GET: /User/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = unitOfWork.userRepository.GetByID(id.Value);
if (user == null)
{
return HttpNotFound();
}
ViewBag.RoleId = new SelectList(unitOfWork.roleRepository.Get(null), "Id", "RoleName", user.RoleId);
return View(user);
}
// POST: /User/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="Id,EmployeeNo,Name,Surname,ContactInfo,RoleId")] User user)
{
if (ModelState.IsValid)
{
unitOfWork.userRepository.Update(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
ViewBag.RoleId = new SelectList(unitOfWork.roleRepository.Get(null), "Id", "RoleName", user.RoleId);
return View(user);
}
// GET: /User/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = unitOfWork.userRepository.GetByID(id.Value);
if (user == null)
{
return HttpNotFound();
}
if (unitOfWork.deviceUsageRepository.Get(null).Where(w => w.UserId == id) != null)
{
ViewBag.Error = 1;
ModelState.AddModelError("", "Nie można kasować uyztkownika z przypisanymi urządzeniami");
}
else
{
ViewBag.Error = 0;
}
return View(user);
}
// POST: /User/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
User user = unitOfWork.userRepository.GetByID(id);
unitOfWork.deviceUsageRepository.Delete(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
unitOfWork.Save();
}
base.Dispose(disposing);
}
}
公共类UserController:Controller
{
//私有设备实体db=新设备实体();
私有UnitOfWork UnitOfWork=新UnitOfWork();
//获取:/User/
公共操作结果索引(字符串名称、字符串姓氏、int?页、字符串提交)
{
列表,其中=新列表();
如果(!string.IsNullOrEmpty(名称))
{
其中.Add(w=>w.Name.Contains(Name));
}
如果(!string.IsNullOrEmpty(姓氏))
{
其中.Add(w=>w.姓氏.Contains(姓氏));
}
var users=unitOfWork.userRepository.Get(其中,null,Page,u=>u.Role);
返回视图(用户);
}
//获取:/User/Details/5
公共行动结果详细信息(int?id)
{
if(id==null)
{
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User=unitOfWork.userRepository.GetByID(id.Value);
//User User=db.Users.Find(id);
if(user==null)
{
返回HttpNotFound();
}
返回视图(用户);
}
//获取:/User/Create
公共操作结果创建()
{
ViewBag.RoleId=new SelectList(unitOfWork.roleRepository.Get(null),“Id”,“RoleName”);
返回视图();
}
//POST:/User/Create
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果创建([Bind(Include=“Id,EmployeeNo,Name,姓氏,ContactInfo,RoleId”)]用户)
{
if(ModelState.IsValid)
{
unitOfWork.userRepository.Insert(用户);
unitOfWork.Save();
返回操作(“索引”);
}
ViewBag.RoleId=新的SelectList(unitOfWork.roleRepository.Get(null),“Id”,“RoleName”,user.RoleId);
返回视图(用户);
}
//获取:/User/Edit/5
公共行动结果编辑(int?id)
{
if(id==null)
{
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User=unitOfWork.userRepository.GetByID(id.Value);
if(user==null)
{
返回HttpNotFound();
}
ViewBag.RoleId=新的SelectList(unitOfWork.roleRepository.Get(null),“Id”,“RoleName”,user.RoleId);
返回视图(用户);
}
//POST:/User/Edit/5
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果编辑([Bind(Include=“Id,EmployeeNo,Name,姓氏,ContactInfo,RoleId”)]用户)
{
if(ModelState.IsValid)
{
unitOfWork.userRepos
public interface IRepository<TEntity> where TEntity: class {
// Your methods
}
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class {
public GenericRepository<TEntity>(EquipmentEntities context) {
// Your constructor
}
// Your implementation
}
public interface IUnitOfWork : IDisposable {
IRepository<Role> RoleRepository { get; }
IRepository<Storage> StorageRepository { get; }
// etc
void Save();
}
public class UnitOfWork : IUnitOfWork {
public UnitOfWork () {
this.context = new EquipmentEntities ();
}
private EquipmentEntities context = null;
private IRepository<Role> roleRepository;
public IRepository<Role> RoleRepository {
get {
if (this.roleRepository == null) {
this.roleRepository = new GenericRepository<Role>(context);
}
return this.roleRepository;
}
}
// etc... other repositories
// etc... your implementation for Save and Dispose
}