C# FormsAuthentication.SetAuthCookie和Request.url在单元测试中失败
我正在开发asp.NETMVC4应用程序并创建单元测试。我有一个帐户控制器和注册方法,它有两个功能:C# FormsAuthentication.SetAuthCookie和Request.url在单元测试中失败,c#,asp.net-mvc,entity-framework,asp.net-mvc-4,moq,C#,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,Moq,我正在开发asp.NETMVC4应用程序并创建单元测试。我有一个帐户控制器和注册方法,它有两个功能: if (this.Request.Url.ToString().Contains("127.0.0")) { user.AddPermission(UserEntity.PermissionType.BETA_ACCESS); } 及 测试在这两条线路上都失败。我目瞪口呆,发现我们不能使用FormsAuthentication.SetAuthCookie,因为FormsAuthenti
if (this.Request.Url.ToString().Contains("127.0.0"))
{
user.AddPermission(UserEntity.PermissionType.BETA_ACCESS);
}
及
测试在这两条线路上都失败。我目瞪口呆,发现我们不能使用FormsAuthentication.SetAuthCookie
,因为FormsAuthentication是一个静态类,所以我尝试了以下解决方法:
public interface IAuthenticationProvider
{
void SetAuthCookie(string username, bool remember);
}
public class FormsAuthWrapper : IAuthenticationProvider
{
public void SetAuthCookie(string userName, bool remember)
{
FormsAuthentication.SetAuthCookie(userName, remember);
}
}
在控制器操作中,我使用了:
_authenticationProvider.SetAuthCookie(model.UserName, false);
在我使用的试验方法中:
var wrapper = new FormsAuthWrapper();
AccountController controller = new AccountController(s, config, wrapper);
但当我调用控制器操作方法时,它仍然在
_authenticationProvider.SetAuthCookie(model.UserName, false);
我的另一个问题与request.url有关,我在测试方法中尝试了这一点:
controller.ControllerContext = CreateStubControllerContext(controller);
var requestStub = Mock.Get(controller.Request);
requestStub.Setup(r => r.UrlReferrer).Returns(new Uri("http://127.0.0.1"));
var RegisterModel = new RegisterModel { UserName = "test2@cc.com", Password = "testpass", ConfirmPassword = "testpass" };
controller.Register(RegisterModel);
但它在控制器操作中在这一行上抛出错误:
if (this.Request.Url.ToString().Contains("127.0.0"))
{
user.AddPermission(UserEntity.PermissionType.BETA_ACCESS);
}
你在问两个截然不同的问题:
iaauthenticationprovider
,而不是具体的formsauthraper
。如果没有完整的web上下文(您永远无法从单元测试中获得),后者将永远无法工作Url
,而不是urlreferer
(它们通常计算为相同的值,但不引用相同的字符串对象)if (this.Request.Url.ToString().Contains("127.0.0"))
{
user.AddPermission(UserEntity.PermissionType.BETA_ACCESS);
}