我目前正在尝试对我正在使用OWIN进行身份验证的新WebAPI项目的身份验证进行单元测试,并且我遇到了在单元测试环境中运行它的问题。
这是我的测试方法:
[TestMethod]
public void TestRegister()
{
using (WebApp.Start<Startup>("localhost/myAPI"))
using (AccountController ac = new AccountController()
{
Request = new System.Net.Http.HttpRequestMessage
(HttpMethod.Post, "http://localhost/myAPI/api/Account/Register")
})
{
var result = ac.Register(new Models.RegisterBindingModel()
{
Email = "testemail@testemail.com",
Password = "Pass@word1",
ConfirmPassword = "Pass@word1"
}).Result;
Assert.IsNotNull(result);
}
}
我收到AggregateException
以获得.Result
以下内部异常:
Result Message:
Test method myAPI.Tests.Controllers.AccountControllerTest.TestRegister
threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: context
Result StackTrace:
at Microsoft.AspNet.Identity.Owin.OwinContextExtensions
.GetUserManager[TManager](IOwinContext context)
at myAPI.Controllers.AccountController.get_UserManager()
...
我已通过调试确认正在调用我的Startup
方法,并调用ConfigurAuth
:
public void ConfigureAuth(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
// Configure the db context and user manager to use a single
// instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>
(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for
// the signed in user
// and to use a cookie to temporarily store information about a
// user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
我尝试了一些东西,但似乎没有任何工作 - 我永远无法获得OWIN背景。以下代码的测试失败:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser()
{ UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
这会调用UserManager
属性:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
失败了:
return _userManager ?? Request.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
NullReferenceException
- Request.GetOwinContext
正在返回null
。
所以我的问题是:我接近这个错误吗?我应该只测试JSON响应吗?或者有“内部”测试OWIN身份验证的好方法吗?
答案 0 :(得分:13)
GetOwinContext调用context.GetOwinEnvironment();
private static IDictionary<string, object> GetOwinEnvironment(this HttpContextBase context)
{
return (IDictionary<string, object>) context.Items[HttpContextItemKeys.OwinEnvironmentKey];
}
和HttpContextItemKeys.OwinEnvironmentKey是一个常量“owin.Environment” 因此,如果您在httpcontext的项目中添加它,它将起作用。
var request = new HttpRequest("", "http://google.com", "rUrl=http://www.google.com")
{
ContentEncoding = Encoding.UTF8 //UrlDecode needs this to be set
};
var ctx = new HttpContext(request, new HttpResponse(new StringWriter()));
//Session need to be set
var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
//this adds aspnet session
ctx.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
var data = new Dictionary<string, object>()
{
{"a", "b"} // fake whatever you need here.
};
ctx.Items["owin.Environment"] = data;
答案 1 :(得分:9)
要确保测试期间OWIN上下文可用(即,在调用Request.GetOwinContext()
时修复空引用异常),您需要在测试项目中安装Microsoft.AspNet.WebApi.Owin
NuGet包。安装完成后,您可以在请求中使用SetOwinContext
扩展方法。
示例:
var controller = new MyController();
controller.Request = new HttpRequestMessage(HttpMethod.Post,
new Uri("api/data/validate", UriKind.Relative)
);
controller.Request.SetOwinContext(new OwinContext());
话虽如此,我同意您的具体用例的其他答案 - 在构造函数中提供AppplicationUserManager实例或工厂。如果您需要直接与测试将使用的上下文进行交互,则必须执行上述SetOwinContext
步骤。
答案 2 :(得分:2)
您可以在AccountController的构造函数中传入UserManager,因此它不会尝试在owinContext中找到它。默认构造函数不是单元测试友好的。
答案 3 :(得分:1)
我倾向于将AccountController注入用户管理器工厂。这样,您就可以轻松交换测试中使用的用户管理器实例。您的默认工厂可以在构造函数中接受请求,以继续为每个请求提供用户管理器的实例。您的测试工厂只返回您想要为其提供测试的用户管理器的实例,我通常会选择一个带有IUserStore的存根实例的实例,因此对用于存储身份信息的后端没有硬性依赖。 / p>
工厂界面和类:
public interface IUserManagerFactory<TUser>
where TUser : class, global::Microsoft.AspNet.Identity.IUser<string>
{
UserManager<TUser> Create();
}
public class UserManagerFactory : IUserManagerFactory<AppUser>
{
private HttpRequestMessage request;
public UserManagerFactory(HttpRequestMessage request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
this.request = request;
}
public UserManager<AppUser, string> Create()
{
return request.GetOwinContext().GetUserManager<UserManager<AppUser>>();
}
}
的AccountController:
public AccountController(IUserManagerFactory<AppUser> userManagerFactory)
{
this.userManagerFactory = userManagerFactory;
}
private UserManager<AppUser> userManager;
public UserManager<AppUser> UserManager
{
get
{
if (this.userManager == null)
{
this.userManager = this.userManagerFactory.Create();
}
return this.userManager;
}
}
测试工厂:
public class TestUserManagerFactory : IUserManagerFactory<AppUser>
{
private IUserStore<AppUser> userStore;
public TestUserManagerFactory()
{
this.userStore = new MockUserStore();
}
public UserManager<AppUser> Create()
{
return new UserManager<AppUser>(new MockUserStore());
}
}
答案 4 :(得分:1)
var data = new Dictionary<string, object>()
{
{"a", "b"} // fake whatever you need here.
};
ctx.Items["owin.Environment"] = data;
使用这段代码并添加到HttpContext而不是ctx,单元测试就像魅力一样。
答案 5 :(得分:0)
这里的答案很有帮助,但是并没有完全让我知道,这是一个完整的例子:
var userStore = new Mock<IUserStore<User>>();
var appUserMgrMock = new Mock<ApplicationUserManager>(userStore.Object);
var owin = new OwinContext();
owin.Set(appUserMgrMock.Object);
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://test.com", null), new HttpResponse(null));
HttpContext.Current.Items["owin.Environment"] = owin.Environment;
请记住要安装所有必需的nuget软件包!