0
我碰到過這段代碼,因爲它引用了HttpContext,所以無法對它進行測試。我如何刪除對HttpContext的依賴關係以使其成爲可測試的?如何從AuthorizationFilterAttribute中重構出HttpContext進行測試?
public class AuthorizeByUserStatus :AuthorizationFilterAttribute
{
private readonly UserStatusEnum status;
public AuthorizeByUserStatus(UserStatusEnum status)
{
this.status = status;
}
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
var authorize = false;
var user = HttpContext.Current.User;
var userIdentity = user.GetIdentity();
if (userIdentity.UserStatus >= status)
{
authorize = true;
}
if (authorize)
{
base.OnAuthorization(actionContext);
}
else
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
}