Home > Backend Development > C++ > How to Mock HttpContext.Current in a Test Init Method?

How to Mock HttpContext.Current in a Test Init Method?

Barbara Streisand
Release: 2025-01-17 02:51:09
Original
769 people have browsed it

How to Mock HttpContext.Current in a Test Init Method?

Mock HttpContext.Current in test initialization 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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template