[英]Asp.net Identity create User without HttpContext
我正在尝试运行一些单元测试,我希望能够使用 Asp.Net Identity 框架创建一个用户,但它需要一个HttpContextBase
。 所以,我决定使用另一个 Stack Overflow 线程建议并模拟一个。 它看起来像这样:
public HttpContext FakeHttpContext
{
get
{
var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
return httpContext;
}
}
public HttpContextBase FakeHttpContextBase
{
get
{
return (new HttpContextWrapper(this.FakeHttpContext));
}
}
这工作正常,直到它到达 Owin 的东西,此时它失败了。
Startup 不会为单元测试运行。 这是我的启动:
[assembly: OwinStartupAttribute(typeof(MyProject.Startup))]
namespace MyProject
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(DataContext.Create);
app.CreatePerOwinContext<IdentityManager>(IdentityManager.Create);
// More Identity Stuff...
}
}
How can I call:
var result = await IdentityManager.Instance(this.FakeHttpContextBase).CreateAsync(user, password);
并让 Startup 运行以便我可以创建此用户?
还是我在这方面完全走错了路?
我正在尝试在 Visual Studio 中使用 NUnit 运行单元测试。
注意:请不要告诉我我应该使用模拟库。 Linq to Object 与 Linq to Entity 的工作方式不同,我正在尝试测试我将在我的应用程序中使用的实际代码,这意味着针对实际数据库对其进行测试。 这一切正常。 这仅是关于如何创建用户。
想出一种不同的方法来实例化用户管理器,仅使用我的 DataContext。
这是最终的测试结果:
private async void SeedUser()
{
using (var context = new DataContext()) {
var newUser = new User() { UserName = "buzzlightyear@pixar.com", Email = "buzzlightyear@pixar.com", Name = "Buzz Lightyear" };
var userManager = new IdentityManager(new UserStore<User>(context));
var result = await userManager.CreateAsync(newUser, "infinityandbeyond");
if (!result.Succeeded) {
Assert.Fail("Failed to set up User for TestBase.");
}
var user = context.Users.FirstOrDefault();
if (user == null) {
Assert.Fail("The User was not found in the database.");
}
this.UserId = user.Id;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.