views:

170

answers:

1

I am using Entity Frameowrk 4.0 and I am calling a stored procedure which returns an ObjectResult and I tried to use MOQ and have not been able to mock ObjectResult. Has anybody been able to mock ObjectResult using moq?

TIA Yaz

+1  A: 

ObjectResult (according to the MSDN docs) is a sealed class as such you cannot mock it. The way Mocking libraries like Moq work is that when you do something like

Mock<Foo> fooMock = new Mock<Foo>();

It generates (using Reflection.Emit and various other magic tricks) a class that looks a little like this

public class FooMockingProxy : Foo {

    public override void This() {
        // Mocking interceptors to support Verify and Setup
    }

    public override string That() {
        // Mocking interceptors to support Verify and Setup
    }

}

i.e. It takes the class (interface) you want to Mock and subclasses it (or implements it in the case of an interface). This allows it to put in instrumentation that allows it to check if a method has been called, or returns a certain value (this supports the various Setup and Verify methods). The restrictions to this method of mocking are:-

  • Sealed classes (can't be subclassed)
  • Private members (can't be accessed from a subclass)
  • Methods or properties classes that are not virtual (and therefore cannot be overriden).

One technique you can take when approaching sealed classes is to wrap them in some kind of interface that is Mockable. Alternatively you can try and Mock an interface that the sealed class implements that only your code consumes.

sighohwell