C# 使用UnitOfWork模拟上下文和存储库
我正在为我们需要构建的一个小应用程序构建单元测试 我已经实现了存储库/工作单元模式。我的经理类实现了工作单元模式 对于给定接口:C# 使用UnitOfWork模拟上下文和存储库,c#,unit-testing,moq,repository-pattern,unit-of-work,C#,Unit Testing,Moq,Repository Pattern,Unit Of Work,我正在为我们需要构建的一个小应用程序构建单元测试 我已经实现了存储库/工作单元模式。我的经理类实现了工作单元模式 对于给定接口: public interface IUserManager { List<ApplicationUser> GetUsers(Expression<Func<ApplicationUser, bool>> filter = null); ApplicationUser GetUser(Expression<Fu
public interface IUserManager
{
List<ApplicationUser> GetUsers(Expression<Func<ApplicationUser, bool>> filter = null);
ApplicationUser GetUser(Expression<Func<ApplicationUser, bool>> filter);
ApplicationUser AddUser(string username, List<string> environmentIds, bool isAdmin = false);
void DeleteUser(string username);
ApplicationUser UpdateUser(string id, List<string> environmentIds, bool isAdmin = false);
IList<string> GetUserRoles(string id);
}
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity> , IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");
TEntity GetById(object id);
void Insert(TEntity entity);
void Delete(object id);
void Delete(TEntity entityToDelete);
void Update(TEntity entityToUpdate);
void Save();
}
公共接口IUserManager
{
列出GetUsers(表达式过滤器=null);
ApplicationUser GetUser(表达式过滤器);
ApplicationUser AddUser(字符串用户名,列表环境ID,bool isAdmin=false);
void DeleteUser(字符串用户名);
ApplicationUser UpdateUser(字符串id,列表环境id,bool isAdmin=false);
IList GetUserRoles(字符串id);
}
我已经实施了
public class UserManager : IUserManager
{
#region private fields
private readonly IRepository<ApplicationUser> _userRepository;
private readonly IRepository<Application> _applicationRepository;
private readonly IRepository<Role> _roleRepository;
private readonly IActiveDirectoryManager _activeDirectoryManager;
#endregion
#region ctor
public UserManager(AppDbContext context, IActiveDirectoryManager activeDirectoryManager)
{
_activeDirectoryManager = activeDirectoryManager;
_userRepository = new Repository<ApplicationUser>(context);
_applicationRepository = new Repository<Application>(context);
_roleRepository = new Repository<Role>(context);
}
#endregion
#region IUserManager
public ApplicationUser AddUser(string username, List<string> applicationIds, bool isAdmin = false)
{
//Get the environments in the list of environmentIds
var applications = _applicationRepository.Get(e => applicationIds.Contains(e.Id)).ToList();
//Get the user from AD
var user = _activeDirectoryManager.GetUser(username);
//set the Id
user.Id = Guid.NewGuid().ToString();
//add the environments to the user
applications.ForEach(x =>
{
user.Applications.Add(x);
});
//if the user is an admin - retrieve the role and add it to the user
if (isAdmin)
{
var role = _roleRepository.Get(r => r.Name == "admin").FirstOrDefault();
if (role != null)
{
user.Roles.Add(role);
}
}
//insert and save
_userRepository.Insert(user);
_userRepository.Save();
//return the user
return user;
}
//removed for brevity
}
公共类用户管理器:IUserManager
{
#区域专用字段
私有只读IRepository用户存储库;
专用只读IRepository\u应用程序存储库;
私人只读电子存储;
专用只读IActiveDirectoryManager\u activeDirectoryManager;
#端区
#区域导体
公共用户管理器(AppDbContext上下文,IActiveDirectoryManager activeDirectoryManager)
{
_activeDirectoryManager=activeDirectoryManager;
_userRepository=新存储库(上下文);
_applicationRepository=新存储库(上下文);
_roleRepository=新存储库(上下文);
}
#端区
#区域经理
公共应用程序用户AddUser(字符串用户名,列表应用程序ID,bool isAdmin=false)
{
//获取环境ID列表中的环境
var applications=_applicationRepository.Get(e=>applicationIds.Contains(e.Id)).ToList();
//从广告中获取用户
var user=\u activeDirectoryManager.GetUser(用户名);
//设置Id
user.Id=Guid.NewGuid().ToString();
//向用户添加环境
applications.ForEach(x=>
{
user.Applications.Add(x);
});
//如果用户是管理员-检索角色并将其添加到用户
如果(isAdmin)
{
var role=_roleRepository.Get(r=>r.Name==“admin”).FirstOrDefault();
if(角色!=null)
{
user.Roles.Add(角色);
}
}
//插入并保存
_userRepository.Insert(用户);
_userRepository.Save();
//返回用户
返回用户;
}
//为简洁起见,请删除
}
我的单元测试类:
[TestClass]
public class UserManagerUnitTest
{
private readonly Mock<IActiveDirectoryManager> _adManager;
private readonly IUserManager _userManager;
private readonly Mock<IRepository<Application>> _applicationRepository;
private readonly Mock<IRepository<ApplicationUser>> _userRepository;
private readonly Mock<IRepository<Role>> _roleRepository;
public UserManagerUnitTest()
{
var context = new Mock<AppDbContext>();
_adManager = new Mock<IActiveDirectoryManager>();
_applicationRepository = new Mock<IRepository<Application>>();
_userRepository = new Mock<IRepository<ApplicationUser>>();
_roleRepository = new Mock<IRepository<Role>>();
_userManager = new UserManager(context.Object, _adManager.Object);
}
[TestMethod]
[TestCategory("AddUser"), TestCategory("Unit")]
public void AddUser_ValidNonAdmin_UserIsAdded()
{
#region Arrange
string username = "testUser";
List<string> applicationIds = new List<string>() {"1", "2", "3"};
_applicationRepository.Setup(x => x.Get(It.IsAny<Expression<Func<Application, bool>>>(),
It.IsAny<Func<IQueryable<Application>, IOrderedQueryable<Application>>>(), It.IsAny<string>()))
.Returns(new List<Application>());
_adManager.Setup(x => x.GetUser(It.IsAny<string>())).Returns(new ApplicationUser());
#endregion
#region Act
var result = _userManager.AddUser(username, applicationIds, false);
#endregion
#region Assert
Assert.IsNotNull(result);
Assert.IsFalse(result.IsAdmin);
#endregion
}
}
[TestClass]
公共类UserManagerUnitTest
{
私有只读模拟管理器;
专用只读IUserManager\u userManager;
私有只读模拟应用程序存储库;
私有只读模拟用户存储库;
私有只读模拟角色存储;
公共用户ManagerUnitTest()
{
var context=newmock();
_adManager=newmock();
_applicationRepository=new Mock();
_userRepository=newmock();
_roleRepository=新模拟();
_userManager=newusermanager(context.Object,_adManager.Object);
}
[测试方法]
[TestCategory(“AddUser”)、TestCategory(“Unit”)]
public void AddUser_ValidNonAdmin_UserIsAdded()
{
#区域排列
字符串username=“testUser”;
List ApplicationId=新列表(){“1”、“2”、“3”};
_applicationRepository.Setup(x=>x.Get(It.IsAny()),
It.IsAny(),It.IsAny())
.返回(新列表());
_Setup(x=>x.GetUser(It.IsAny()).Returns(newapplicationuser());
#端区
#区域法
var result=\u userManager.AddUser(用户名、应用程序ID、false);
#端区
#区域断言
Assert.IsNotNull(结果);
Assert.IsFalse(result.IsAdmin);
#端区
}
}
最后是存储库界面:
public interface IUserManager
{
List<ApplicationUser> GetUsers(Expression<Func<ApplicationUser, bool>> filter = null);
ApplicationUser GetUser(Expression<Func<ApplicationUser, bool>> filter);
ApplicationUser AddUser(string username, List<string> environmentIds, bool isAdmin = false);
void DeleteUser(string username);
ApplicationUser UpdateUser(string id, List<string> environmentIds, bool isAdmin = false);
IList<string> GetUserRoles(string id);
}
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity> , IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");
TEntity GetById(object id);
void Insert(TEntity entity);
void Delete(object id);
void Delete(TEntity entityToDelete);
void Update(TEntity entityToUpdate);
void Save();
}
公共接口假定,其中tenty:class
{
IEnumerable Get(表达式过滤器=null,
Func orderBy=null,字符串includeProperties=“”);
TEntity GetById(对象id);
无效插入(TEntity实体);
作废删除(对象id);
无效删除(TEntity entityToDelete);
无效更新(TEntity entityToUpdate);
作废保存();
}
和执行:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly AppDbContext _context;
internal DbSet<TEntity> DbSet;
public Repository(AppDbContext context)
{
_context = context;
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 prop in includeProperties.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(prop);
}
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 void Get(Expression<Func<Application, bool>> expression, Func<IQueryable<Application>> func, IOrderedQueryable<Application> orderedQueryable)
{
throw new NotImplementedException();
}
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;
}
public void Save()
{
_context.SaveChanges();
}
}
公共类存储库:i存储,其中tenty:class
{
私有只读AppDbContext\u上下文;
内部数据库集;
公共存储库(AppDbContext上下文)
{
_上下文=上下文;
DbSet=_context.Set();
}
公共虚拟IEnumerable Get(表达式筛选器=null,
Func orderBy=null,字符串includeProperties=“”)
{
IQueryable query=DbSet;
if(过滤器!=null)
query=query.Where(过滤器);
foreach(includeProperties.Split中的var prop(新字符[]{',},StringSplitOptions.RemoveEmptyEntries))
{
query=query.Include(prop);
}
if(orderBy!=null)
{
returnorderby(query.ToList();
}
其他的
{
返回query.ToList();
}
}
公共虚拟实体GetById(对象id)
{
返回DbSet.Find(id);
}
公共虚拟空白插入(TEntity实体)
{
添加(实体);
}
公共虚拟无效删除(对象id)
{
TEntity entityToDelete=DbSet.Find(id);
删除(entityToDelete);
}
public void Get(表达式表达式、Func Func、IOrderedQueryable orderedQueryable)
{
抛出新的NotImplementedException();
}
公共虚拟无效删除(TEntity entityToDelete)
{
if(_context.Entry(entityToDelete.State==EntityState.Detached)
{
数据库集连接(entityToDelete);
}
DbSet.Remove(entityToDelete);
}
公共虚拟无效更新(TEntity entityToUpdate)
{
数据库集附加(实体更新);
_context.Entry(entityToUpdate.State=EntityState.Modified;
}
公共作废保存()
{
_SaveChanges();
}
}
我的问题在于
public UserManager(AppDbContext context, IActiveDirectoryManager activeDirectoryManager)
{
_activeDirectoryManager = activeDirectoryManager;
_userRepository = new Repository<ApplicationUser>(context);
_applicationRepository = new Repository<Application>(context);
_roleRepository = new Repository<Role>(context);
}
public UserManager(IRepository<ApplicationUser> userRepository, IRepository<Application> applicationRepository, IRepository<Role> roleRepository, IActiveDirectoryManager activeDirectoryManager)
{
_activeDirectoryManager = activeDirectoryManager;
_userRepository = userRepository;
_applicationRepository = applicationRepository;
_roleRepository = roleRepository;
}