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

时间:2017-11-09 09:43:19

标签: 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:未将对象引用设置为实例   一个对象。

这是我的单元测试:

        [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);
        }

1 个答案:

答案 0 :(得分:0)

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的代码