Home >Backend Development >C++ >How to Mock HttpContext.Current in a Test Init Method?
Since HttpContextBase inherits from ControllerContext, and HttpContext inherits from the base class library, mocking HttpContext.Current in the Init method will encounter inheritance conflicts.
Alternatives using HttpContext
Fortunately, we can mock the HttpContext directly, which is enough to operate IPrincipal (User) and IIdentity:
<code class="language-csharp">HttpContext.Current = new HttpContext( new HttpRequest("", "http://tempuri.org", ""), new HttpResponse(new StringWriter()) ); // 用户已登录 HttpContext.Current.User = new GenericPrincipal( new GenericIdentity("username"), new string[0] ); // 用户已注销 HttpContext.Current.User = new GenericPrincipal( new GenericIdentity(String.Empty), new string[0] );</code>
This code ensures that the HttpContext is mocked in your controller and in any libraries called in the Init method.
The above is the detailed content of How to Mock HttpContext.Current in a Test Init Method?. For more information, please follow other related articles on the PHP Chinese website!