这是我的代码:
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);
}
答案 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]
);