对部分模拟的期望 - NullReference 异常
我在使用 Rhino Mocks 进行部分模拟时遇到问题:
var authentication = (FormsAuthenticationService)_mocks.PartialMock(
typeof(FormsAuthenticationService));
Expect.Call( delegate{ authentication.SetAuthCookie(null, null); }).IgnoreArguments();
..并且我在“Expect”上得到 NullReferenceException。 行..
我将添加 FormsAuthenticationService
实现 IAuthentication
I've a problem with partial mocking using Rhino Mocks:
var authentication = (FormsAuthenticationService)_mocks.PartialMock(
typeof(FormsAuthenticationService));
Expect.Call( delegate{ authentication.SetAuthCookie(null, null); }).IgnoreArguments();
..and I get NullReferenceException on "Expect." line..
I will just add that FormsAuthenticationService
implements IAuthentication
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您尝试模拟物理类而不是接口有充分的理由吗? 我问这个问题是因为模拟 FormsAuthenticationService 存在两个潜在问题:
该类可能没有默认值
无参数构造函数(其中
情况下,您需要指定一个
的重载方法
mocks.PartialMock)。
SetAuthCookie 必须是虚拟的。 模拟框架通常只能模拟非密封类,并且只能模拟此类的虚拟成员。
为了解决这些问题,我建议改为模拟 IAuthentication。 模拟接口没有这些限制。 这是您要编写的代码:
Is there a good reason you're trying to mock the physical class, rather than the interface? I ask this because there are 2 potential problems with mocking FormsAuthenticationService:
The class may not have a default
parameterless constructor (in which
case, you need to specify an
overloaded method of
mocks.PartialMock).
The SetAuthCookie has to be virtual. Mock frameworks typically can mock only non-sealed classes, and only the virtual members of such a class.
To get around these problems, I'd recommend mocking IAuthentication instead. Mocking interfaces doesn't have these limitations. Here's the code you'd write: