Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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". 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) ?

like image 448
ripper234 Avatar asked May 31 '09 11:05

ripper234


People also ask

Can sealed class be mocked?

Create Mock for Sealed Class with Internal Constructor Even the sealed class has only an internal constructor, you can still create a mock, call its members and verify the results.

Can I instantiate a sealed class?

A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.

How do you call a sealed class method?

If you want to declare a method as sealed, then it has to be declared as virtual in its base class. In the following code, create a sealed class SealedClass and use it from Program. If you run this code then it will work fine.

Can we instantiate sealed class in C#?

A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated. The design intent of a sealed class is to indicate that the class is specialized and there is no need to extend it to provide any additional functionality through inheritance to override its behavior.


1 Answers

Rhino Mocks appears to be catching and handling this exception. You only see it in the VS.NET Debugger if you've enabled exceptions as breakpoints. It appears that you can safely continue running past this exception breakpoint and it all works as expected.

like image 186
Tony O'Hagan Avatar answered Nov 15 '22 13:11

Tony O'Hagan