我对这篇文章有类似的问题...
How can use Microsoft Fakes to mock User.Identity.Name
当试图按照给出的答案之一时,我遇到了创建其中一个对象StubIPrincipal的问题。
我已经为System.Web添加了Fakes。我在帖子后面添加了Fakes for System。当我仍然无法创建存根时,我还添加了Fums for System.Security,其中IPrincipal存在。创造用户仍然没有运气。
这是我用来尝试和存根HttpContext的方法,它正在运行。我也需要能够获得HttpContext.User.Identity。
public static HttpContextBase FakeHttpContext(string url = "")
{
var cookies = new HttpCookieCollection();
var session = new StubHttpSessionStateBase();
var server = new StubHttpServerUtilityBase();
var items = new ListDictionary();
var user = new StubIPrincipal // Cannot resolve symbol 'StubIPrincipal'
{
};
var browser = new StubHttpBrowserCapabilitiesBase
{
IsMobileDeviceGet = () => false
};
var request = new StubHttpRequestBase
{
AppRelativeCurrentExecutionFilePathGet = () => url,
ApplicationPathGet = () => url,
CookiesGet = () => cookies,
UserAgentGet = () => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
BrowserGet = () => browser,
UrlGet = () => !string.IsNullOrEmpty(url) ? new Uri(url) : null
};
var response = new StubHttpResponseBase
{
CookiesGet = () => cookies,
ApplyAppPathModifierString = s => s,
StatusCodeGet = () => (int)HttpStatusCode.OK
};
var context = new StubHttpContextBase
{
RequestGet = () => request,
ResponseGet = () => response,
SessionGet = () => session,
ServerGet = () => server,
ItemsGet = () => items
};
return context;
}
我尝试的另一件事就是手动创建用户,并将其添加到上下文中。
System.Security.Principal.IPrincipal user;
var winId = new WindowsIdentity("u1332304");
user = new WindowsPrincipal(winId);
context.User = user;
当我这样做时,我在context.User对象上得到一个Not Implemented错误。
答案 0 :(得分:0)
为了让我存根IPrincipal
,我不得不伪造System
,而mscorlib.fakes
又加上System.Security.Principal.Fakes.StubIPrincipal
。这使我能够在我的代码中使用User.Identity.Name
。
然后我通过执行以下操作来追踪using (AccountController controller = new AccountController())
{
StubHttpContextBase stubHttpContext = new StubHttpContextBase();
controller.ControllerContext = new ControllerContext(stubHttpContext, new RouteData(), controller);
StubIPrincipal principal = new StubIPrincipal();
principal.IdentityGet = () =>
{
return new StubIIdentity
{
NameGet = () => "bob"
};
};
stubHttpContext.UserGet = () => principal;
}
:
{{1}}
答案 1 :(得分:0)
您可以在不使用Microsoft Fakes(或任何模拟库)的情况下模拟HttpContext.Current.User
。见上一个问题(免责声明:由我回答):Mock HttpContext.Current in Test Init Method