最小起订量IIdentity [英] Moq custom IIdentity
问题描述
我创建了一个自定义RoleProvider(标准Web表单,没有mvc),我想对其进行测试.提供程序本身与IIdentity的自定义实现集成(具有一些附加属性).
I created a custom RoleProvider (standard webforms, no mvc) and I would like to test it. The provider itself integrates with a custom implementation of IIdentity (with some added properties).
我现在有这个:
var user = new Mock<IPrincipal>();
var identity = new Mock<CustomIdentity>();
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
identity.SetupGet(id => id.IsAuthenticated).Returns(true);
identity.SetupGet(id => id.LoginName).Returns("test");
// IsAuthenticated is the implementation of the IIdentity interface and LoginName
但是,当我在VS2008中运行此测试时,会收到以下错误消息:
However when I run this test in VS2008 then I get the following error message:
在不可覆盖的成员上的无效设置:id => id.IsAuthenticated
Invalid setup on a non-overridable member: id => id.IsAuthenticated
为什么会这样?最重要的是,我需要怎么做才能解决它?
Why is this happening? And most important, what do I need to do to solve it?
格里斯,克里斯.
推荐答案
您应该模拟IIdentity(而不是CustomIdentity-仅在要模拟的变量在接口中声明的情况下才可以)或将使用的变量声明为虚拟.
You should mock IIdentity (instead of CustomIdentity - only possible if the variables you are mocking are declared in the interface) or declare the used variables as virtual.
>
要标记为虚拟,请执行以下操作:在具体的类CustomIdentity中,使用
To mark as virtual, do this: In your concrete class CustomIdentity, use
public virtual bool isAuthenticated { get; set; }
代替
public bool isAuthenticated { get; set; }
Moq和其他免费的模拟框架不允许您模拟具体类类型的成员和方法,除非它们被标记为虚拟的.
Moq and other free mocking frameworks doesn't let you mock members and methods of concrete class types, unless they are marked virtual.
最后,您可以自己手动创建模拟.您可以将CustomIdentity继承到测试类,该类将根据需要返回值.像这样:
Finally, you could create the mock yourself manually. You could inherit CustomIdentity to a test class, which would return the values as you wanted. Something like:
internal class CustomIdentityTestClass : CustomIdentity
{
public new bool isAuthenticated
{
get
{
return true;
}
}
public new string LoginName
{
get
{
return "test";
}
}
}
此类仅用于测试,作为您的CustomIdentity的模拟.
This class would be only used in testing, as a mock for your CustomIdentity.
-编辑
在评论中提问.
这篇关于最小起订量IIdentity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!