【发布时间】:2016-06-29 22:47:19
【问题描述】:
我想知道是否有人可以帮助我。
我正在为特定控制器编写单元测试。该控制器继承自 BaseController 并且该 BaseController 具有以下属性:
private ApplicationUserManager userManager;
public ApplicationUserManager UserManager
{
get { return this.userManager ?? this.Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
set { this.userManager = value; }
}
ApplicationUserManager 的 ctor 是:
public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService)
: base(store)
{
this.EmailService = emailService;
var dataProtectionProvider = Startup.DataProtectionProvider;
this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
这就是我模拟 ApplicatonUserManager 类的方法:
var store = new Mock<IUserStore<ApplicationUser>>();
var emailService = new Mock<IIdentityMessageService>();
var applicationUserManager = new Mock<ApplicationUserManager>(store.Object, emailService.Object);
this.targetController.UserManager = applicationUserManager.Object;
var dataprotectionprovided = new Mock<IDataProtectionProvider>();
applicationUserManager.Setup(r => r.UserTokenProvider).Returns(new DataProtectorTokenProvider<ApplicationUser, string>(dataprotectionprovided.Object.Create("ASP.NET Identity")));
this.targetController.UserManager = applicationUserManager.Object;
我试图模拟这个,但因为这不是虚拟财产(UserTokenProvider)它不允许我,我得到这个异常:
System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: r => r.UserTokenProvider
谁能帮我解决这个问题?我只是想模拟它以测试从具有该属性的 BaseController 继承的控制器。
谢谢
【问题讨论】:
-
与其模拟 ApplicationUserManager,你可以为它创建另一个构造函数并通过备用构造函数实例化它吗?
标签: c# asp.net-mvc unit-testing moq asp.net-identity-2