我目前想的单元测试我使用OWIN验证编写一个新的Web API项目的认证,并且我有一个单元测试环境中运行它的问题。
这是我的测试方法:
[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 = "[email protected]",
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认证?
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;
为了确保一个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
以上步骤是必要的。
你可以只通过在的AccountController的构造函数中的UserManager,所以它不会试图找到它在owinContext。默认构造函数是不是单元测试友好。
我倾向于做的是与用户管理器工厂注入的AccountController。这样,你可以很容易地掉了在测试中使用的用户管理器的实例。您的默认出厂可以请求在构造函数中继续根据用户的经理的要求提供的实例。您的测试工厂只是返回要与提供您的测试用户管理器的情况下,我通常去一个需要IUserStore的存根实例,以便有用于存储身份信息在后端没有硬性的依赖性。
工厂接口和类:
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());
}
}
var data = new Dictionary<string, object>()
{
{"a", "b"} // fake whatever you need here.
};
ctx.Items["owin.Environment"] = data;
使用该片的代码,并加入到的HttpContext代替CTX和单元测试工作就像一个魅力。
这里的答案帮助,但并没有完全让我有一路,这里有一个完整的例子:
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包!