起订量定制 IIidentity
我创建了一个自定义 RoleProvider(标准 Web 表单,无 MVC),我想测试它。 提供程序本身与 IIdentity 的自定义实现集成(带有一些附加属性)。
我现在有这个:
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 中运行此测试时,我收到以下错误消息:
Invalid setup on a non-overridable member: id => id.IsAuthenticated
为什么会发生这种情况? 最重要的是,我需要做什么来解决这个问题?
格兹,克里斯。
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).
I have this at the moment:
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
However when I run this test in VS2008 then I get the following error message:
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?
Grz, Kris.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该模拟 IIdentity(而不是 CustomIdentity - 仅当您模拟的变量在接口中声明时才可能)或将使用的变量声明为虚拟变量。
要标记为虚拟,请执行以下操作:在具体类 CustomIdentity 中,使用
而不是
Moq 和其他免费模拟框架不允许您模拟具体类类型的成员和方法,除非它们被标记为虚拟。
最后,您可以自己手动创建模拟。 您可以将 CustomIdentity 继承到测试类,该类将返回您想要的值。 类似于:
此类仅用于测试,作为您的 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.
To mark as virtual, do this: In your concrete class CustomIdentity, use
instead of
Moq and other free mocking frameworks doesn't let you mock members and methods of concrete class types, unless they are marked virtual.
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:
This class would be only used in testing, as a mock for your CustomIdentity.
--EDIT
Answer to question in comments.
您是在嘲笑接口 IIdentity,还是在嘲笑您的自定义类型?
如果没有更完整的代码片段可供查看,我猜测它在抱怨 IsAuthenticated 在您的自定义实现中未标记为虚拟。 但是,只有当您针对具体类型而不是接口进行模拟时,才会出现这种情况。
Are you mocking against the interface IIdentity, or mocking against your custom type?
Without having a fuller code snippet to look at, I am guessing that it is complaining that the IsAuthenticated is not marked as virtual in your custom implementation. However, this could only be the case if you were mocking against the concrete type, not the interface.