我正在尝试运行一些单元测试,我希望能够使用Asp.Net Identity框架创建一个User,但是它需要一个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的东西,这时它失败了。
启动不会针对单元测试运行。这是我的创业公司:
[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);
并使启动程序运行,以便我可以创建该用户?
或者我是否完全走错了道路?
我正在尝试在Visual Studio中使用NUnit运行单元测试。
注意:请不要告诉我我应该使用模拟库。 Linq to Object与Linq to Entity的工作方式不同,我正在尝试测试将在我的应用程序中使用的实际代码,这意味着要针对实际数据库进行测试。一切都很好。这仅与如何创建用户有关。
[想出了一种仅使用DataContext实例化用户管理器的方法。
这是最终测试结果:
private async void SeedUser()
{
using (var context = new DataContext()) {
var newUser = new User() { UserName = "[email protected]", Email = "[email protected]", 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;
}
}