我有一个WebApi方法看起来或多或少像这样:
public async Task<HttpResponseMessage> Get(Guid id) { var foo = await Store.GetFooAsync(id); if (foo.BelongsTo != User.Identity.Name) throw new HttpResponseException(HttpStatusCode.Forbidden); //return foo here }
这似乎在实际应用程序中工作正常,其中自定义IHttpModule在HttpContext.User和Thread.CurrentPrincipal中设置主体.
但是,从单元测试中调用时:
Thread.CurrentPrincipal = principal; var response = controller.Get(id).Result;
用户在等待(即继续)后重置,因此测试失败.在R#8下运行时会发生这种情况,R#7没有发生这种情况.
我的解决方法是在第一次等待之前保存当前的主体,但它只是满足测试运行者需求的黑客.