我正在编写用于在ASP.NET 5
应用程序中管理用户的UI 。我需要显示UI中UserManager返回的任何错误。我IdentityResult
在视图模型中传回了错误,但是在测试我的代码时,我有些失落。
什么是嘲笑的最佳方法UserManager
的ASP.NET 5
?
我是否应该继承UserManager
并覆盖所有正在使用的方法,然后将其版本注入UserManager
到Controller
测试项目中的实例中?
我已经在MVC音乐商店示例应用程序的帮助下对其进行了管理。
在单元测试类中,我像这样设置数据库上下文和UserManager:
public class DatabaseSetupTests : IDisposable
{
private MyDbContext Context { get; }
private UserManager<ApplicationUser> UserManager { get; }
public DatabaseSetupTests()
{
var services = new ServiceCollection();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase());
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MyDbContext>();
// Taken from https://github.com/aspnet/MusicStore/blob/dev/test/MusicStore.Test/ManageControllerTest.cs (and modified)
// IHttpContextAccessor is required for SignInManager, and UserManager
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
var serviceProvider = services.BuildServiceProvider();
Context = serviceProvider.GetRequiredService<MyDbContext>();
UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
}
....
}
然后,我可以在单元测试中使用UserManager,例如:
[Fact]
public async Task DontCreateAdminUserWhenOtherAdminsPresent()
{
await UserManager.CreateAsync(new ApplicationUser { UserName = "[email protected]" }, "IDoComplyWithTheRules2016!");
...
}
如果您的Dependency Injector无法解析IHttpContextAccessor,则将无法创建UserManager实例,因为它依赖于它。我认为(这只是一个假设),在Asp.Net 5中,UserManager确实会在您为用户更改Cookie(声明,角色...)时声明基于Cookie的声明,因此需要一些HttpContext进行登录/注销操作和cookie访问。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句