我正在使用NUnit,NSubstitute为一个使用Ninject和通用存储库的项目引入自动测试。
对于回归测试,我将在内存中替换通用存储库以防止使用数据库。
另外,为了测试服务的安全性限制,我正在嘲笑安全服务,如下所示:
public class SecurityService : ISecurityService
{
#region Properties
private IScopedDataAccess DataAccess { get; }
private IMappingService MappingService { get; }
#endregion
#region Constructor
public SecurityService(IScopedDataAccess scopedDataAccess, IMappingService mappingService)
{
DataAccess = scopedDataAccess;
MappingService = mappingService;
}
#endregion
#region Methods
public virtual string GetUsername()
{
return HttpContext.Current.User.Identity.Name;
}
public AppUserSecurityProfileServiceModel GetCurrentUserData()
{
var username = GetUsername();
var userDataModel = DataAccess.AppUserRepository.AllNoTracking.FirstOrDefault(u => u.Username == username);
if (userDataModel == null)
return null;
var ret = MappingService.Mapper.Map<AppUserSecurityProfileServiceModel>(userDataModel);
return ret;
}
public virtual int GetCurrentUserId()
{
var userData = GetCurrentUserData();
if (userData == null)
throw new SecurityException($"No user data could be fetched for - {GetUsername()}");
return userData.AppUserId;
}
public bool IsInRole(UserRoleEnum role, int? userId = null)
{
int actualUserId = userId ?? GetCurrentUserId();
var hasRole = DataAccess.AppUserXUserRoleRepository.AllNoTracking.Any(x => x.AppUserId == actualUserId && x.UserRoleId == (int) role);
return hasRole;
}
public bool CanPerformAction(UserActionEnum action, int? userId = null)
{
int actualUserId = userId ?? GetCurrentUserId();
var hasAction = DataAccess.AppUserXUserRoleRepository.AllNoTracking
.Where(x => x.AppUserId == actualUserId)
.Join(DataAccess.UserRoleRepository.AllNoTracking, xRole => xRole.UserRoleId, role => role.UserRoleId, (xRole, role) => role)
.Join(DataAccess.UserRoleXUserActionRepository.AllNoTracking, xRole => xRole.UserRoleId, xAction => xAction.UserRoleId,
(role, xAction) => xAction.UserActionId)
.Contains((int) action);
return hasAction;
}
// other methods can appear here in the future
#endregion
}
每个回归测试都会假装当前用户:
public void FakeCurrentUser(int userId)
{
var userRef = DataAccess.AppUserRepository.AllNoTracking.FirstOrDefault(u => u.AppUserId == userId);
var securitySubstitude = Substitute.ForPartsOf<SecurityService>(Kernel.Get<IScopedDataAccess>(), Kernel.Get<IMappingService>());
securitySubstitude.When(x => x.GetUsername()).DoNotCallBase();
securitySubstitude.GetUsername().Returns(userRef?.Username ?? "<none>");
securitySubstitude.When(x => x.GetCurrentUserId()).DoNotCallBase();
securitySubstitude.GetCurrentUserId().Returns(userId);
Kernel.Rebind<ISecurityService>().ToConstant(securitySubstitude);
}
基本上,它需要注意替换基于上下文的方法(例如我的HttpContext
),但保留其他方法。
每次测试的服务都将在初始化后进行实例化,因此我确信会注入相应的实例。
问题:可以像这样模拟服务还是反模式?
答案 0 :(得分:1)
您对此方法有特别关注吗?在这种情况下似乎可行。
我个人喜欢避免部分嘲笑,因为那时我必须更仔细地跟踪哪些部分是真实的/将要调用真实代码与哪些部分被伪造出来。如果您可以灵活地在此处更改代码,则可以将forEach()
相关内容推送到另一个依赖项(我认为是策略模式),然后将其假冒。
类似的东西:
collect()
现在,您可以自由地为您的测试传递HttpContext
的替代实现(可以手动实现或使用模拟库)。这解决了我对部分模拟的初步关注,因为我知道所有被测试的public interface IUserInfo {
string GetUsername();
int GetCurrentUserId();
}
public class HttpContextUserInfo : IUserInfo {
public string GetUsername() { return HttpContext.Current.User.Identity.Name; }
public int GetCurrentUserId() { ... }
}
public class SecurityService : ISecurityService
{
private IScopedDataAccess DataAccess { get; }
private IMappingService MappingService { get; }
// New field:
private IUserInfo UserInfo { get; }
// Added ctor argument:
public SecurityService(IScopedDataAccess scopedDataAccess, IMappingService mappingService, IUserInfo userInfo)
{ ... }
public AppUserSecurityProfileServiceModel GetCurrentUserData()
{
var username = UserInfo.GetUsername();
var userDataModel = DataAccess.AppUserRepository.AllNoTracking.FirstOrDefault(u => u.Username == username);
...
return ret;
}
public bool IsInRole(UserRoleEnum role, int? userId = null)
{
int actualUserId = userId ?? UserInfo.GetCurrentUserId();
var hasRole = ...;
return hasRole;
}
public bool CanPerformAction(UserActionEnum action, int? userId = null)
{
int actualUserId = userId ?? UserInfo.GetCurrentUserId();
var hasAction = ...;
return hasAction;
}
}
都在调用它的真实代码,我可以操纵测试依赖项来运用该代码的不同部分。成本是我们现在要担心的另一个类(可能是另一个接口;我已经使用了一个但你可以坚持使用虚拟方法的单个类),这会增加解决方案的复杂性。
希望这有帮助。