简体   繁体   English

模拟在RhinoMocks中返回密封类的方法

[英]Mocking a method that returns a sealed class in RhinoMocks

Running this code: 运行此代码:

_foo = MockRepository.GenerateStub<IBar>();
_foo.Stub(x => x.Foo()).Return("sdf");

When 什么时候

public interface IBar
{
   string Foo();
}

public class Bar : IBar
{
   public string Foo()
   {
      throw new NotImplementedException();
   }
}

throws NotSupportedException - "Can't create mocks of sealed classes". 抛出NotSupportedException - “无法创建密封类的模拟”。 I understand why you can't mock a sealed class (although there are solutions in TypeMock), but what's the problem with mocking a class that returns a sealed class (string) ? 我明白为什么你不能模拟一个密封的类(虽然在TypeMock中有解决方案),但是模拟一个返回密封类(字符串)的类有什么问题?

Rhino Mocks appears to be catching and handling this exception. Rhino Mocks似乎正在捕捉并处理此异常。 You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. 如果您已将异常作为断点启用,则只能在VS.NET调试器中看到它。 It appears that you can safely continue running past this exception breakpoint and it all works as expected. 您似乎可以安全地继续运行此异常断点,并且它都按预期工作。

This happens when you have NOT got "Just my code" enabled under Tools->Options->Debugging->General, and you have CLR exceptions, "Thrown" selected under Debug->Exceptions. 如果您没有在Tools-> Options-> Debugging-> General下启用“Just my code”,并且在Debug-> Exceptions下选择了“Thrown”,则会发生这种情况。 Easiest way to fix it is enable "just my code" under Tools->Options->Debugging->General. 最简单的解决方法是在工具 - >选项 - >调试 - >常规下启用“仅我的代码”。

在此输入图像描述

Your code works properly. 您的代码正常运行。 You likely have some other code not shown which is causing the problem. 您可能还有一些其他代码未显示导致问题。 Post your whole unit test here and we'll diagnose the issue for you. 在这里发布您的整个单元测试,我们将为您诊断问题。

I have the same problem, it has to be some VS studio debug setting or some insufficient access rights for rhino mocks i guess. 我有同样的问题,它必须是一些VS工作室调试设置或我猜的犀牛模拟的一些不充分的访问权限。 I am pretty sure that its not the code that is causing this. 我很确定它不是造成这种情况的代码。

I second that - It's not an issue with code. 我是第二个 - 这不是代码问题。 It is VS debug setting. 这是VS调试设置。

I get the same exception while on debug on the code below, while trying to send Arg.Is.Anything as a parameter to a stub. 我在下面的代码调试时得到了同样的异常,同时尝试将Arg.Is.Anything作为参数发送到存根。

mockPermissionManager.Stub(item => item.HasAccess(Arg<string>.Is.Anything)).Return(true);

The exception is handled and code/mocking works as expected, just do F5 处理异常并且代码/模拟按预期工作,只需执行F5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM