c# - 如何使用 HttpContext 创建单元测试以在方法内进行授权?

标签 c# asp.net visual-studio unit-testing

这是我的代码:

public static ApiResponseBase BookActivity(ActivityBookApiRequest request)
        {
            var user = HttpContext.Current.User;
            if (string.IsNullOrEmpty(user.Identity.Name))
            {
                return new ActivityBookApiResponse
                {
                    StatusCode = HttpStatusCode.Unauthorized,
                    ErrorCode = "ERAGPR01"
                };
            }
            return null;
        }

如何为该代码创建单元测试?

我创建了单元测试,但仍然失败,因为 HttpContext.Current.User给出的错误:

System.NullReferenceException: Object reference not set to an instance of an object.

这是我的单元测试:

        [TestMethod]
        public void Book_Null_ReturnBadRequest()
        {
            var expectedResult = new ActivityBookApiResponse
            {
                StatusCode = HttpStatusCode.Unauthorized,
                ErrorCode = "ERAGPR01"
            };
            var actualResult = ActivityLogic.BookActivity(null);
            Assert.AreEqual(expectedResult.StatusCode, actualResult.StatusCode);
            Assert.AreEqual(expectedResult.StatusCode, actualResult.StatusCode);
        }

最佳答案

HttpContext.Current 是静态的,可以分配:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

代码来自Mock HttpContext.Current in Test Init Method

关于c# - 如何使用 HttpContext 创建单元测试以在方法内进行授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47198502/

相关文章:

asp.net - 在 iis 7.5 中设置物理内存限制是否会导致垃圾收集器更积极地运行?

c# - asp.net core + ef6 + mysql

javascript - 从 JavaScript asp.net 调用按钮单击不起作用

.net - asp.net网站中的CSS文件

c# - 为什么我的命名空间引用在 Visual Studio 中不断中断?

c# - byte[] 不包含 concat 的定义

c# - 在运行时停止/启动 WCF MEX 服务

visual-studio - 为什么在构建安装项目时会得到 "An error occurred while validating. HRESULT = ' 8000400 5'"?

c# - 文化(语言)发生变化时的动态字体大小

c# - 编译器构建错误 : The call is ambiguous between the following methods or properties