在MVC中模拟FormsAuthentication
本文关键字:FormsAuthentication 模拟 MVC | 更新日期: 2023-09-27 17:52:54
我有下面的代码,并希望测试场景时,FormsAuthentication返回null。我如何做到这一点,我假设使用mock,因为FormsAuthentication是一个带有静态方法的密封类。我正在使用RhinoMocks。
public PaxiumPrincipal CreatePrincipalFromCookie(string cookieValue)
{
var authTicket = FormsAuthentication.Decrypt(cookieValue);
if (authTicket == null)
{
return null;
};
var userPrincipal = new PaxiumPrincipal(new GenericIdentity(authTicket.Name), null);
return userPrincipal;
}
我没有看到任何FormsAuthentication.Decrypt()返回null的证据,除了这里描述的一个bug。相反,它会在cookie无效时抛出ArgumentException
。我认为你应该测试一下cookie是否还没有过期。
但是为了便于讨论,以下是您如何TDD一个密封类:
为你需要的所有方法创建一个接口
进入你的生产代码:
public interface IFormsAuthentication
{
FormsAuthenticationTicket Decrypt(string cookieValue);
}
在密封类
周围创建包装器这也是你的生产代码:
public class MyFormsAuthentication : IFormsAuthentication
{
public FormsAuthenticationTicket Decrypt(string cookieValue)
{
return FormsAuthentication.Decrypt(cookieValue);
}
}
更改要测试的方法
应该使用它所提供的IFormsAuthentication
对象而不是密封类。在生产中,这应该是您的包装器。显然,这是在您的生产代码…
public class PaxiumPricipalCreator
{
IFormsAuthentication _formsAuthentication;
public PaxiumPricipalCreator(IFormsAuthentication formsAuthentication)
{
_formsAuthentication = formsAuthentication;
}
public PaxiumPrincipal CreatePrincipalFromCookie(string cookieValue)
{
var authTicket = _formsAuthentication.Decrypt(cookieValue);
if (authTicket == null)
{
return null;
};
var userPrincipal = new PaxiumPrincipal(new GenericIdentity(authTicket.Name), null);
return userPrincipal;
}
}
创建一个带有模拟验证器的单元测试(该示例位于MSTest中)
这是你的测试代码:[TestClass]
public class PaxiumPricipalCreatorTests
{
[TestMethod]
public void Returns_NULL_principal_when_IFormsAuthentication_returns_null()
{
var mockAuthenticator = new NullReturningFormsAuthentication();
var principalCreator = new PaxiumPricipalCreator(mockAuthenticator);
var actual = principalCreator.CreatePrincipalFromCookie(string.Empty);
Assert.IsNull(actual);
}
public class NullReturningFormsAuthentication : IFormsAuthentication
{
public FormsAuthenticationTicket Decrypt(string cookieValue)
{
return null;
}
}
}