Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RhinoMocks, how do you mock or stub a concrete class without an empty constructor?

Mocking a concrete class with Rhino Mocks seems to work pretty easy when you have an empty constructor on a class:

public class MyClass{      public MyClass() {} } 

But if I add a constructor that takes parameters and remove the one that doesn't take parameters:

public class MyClass{      public MyClass(MyOtherClass instance) {} } 

I tend to get an exception:

System.MissingMethodException : Can't find a constructor with matching arguments

I've tried putting in nulls in my call to Mock or Stub, but it doesn't work.

Can I create mocks and stubs of concrete classes that lack parameter-less constructors?

like image 845
Mark Rogers Avatar asked Aug 17 '09 23:08

Mark Rogers


People also ask

Can you mock a concrete class?

5 Answers. Show activity on this post. In theory there is absolutely no problem mocking a concrete class; we are testing against a logical interface (rather than a keyword interface ), and it does not matter whether that logical interface is provided by a class or interface . In practice .

How do I mock a class without an interface?

Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method. This leaves me wonder if it is necessary at all to create an interface for every class I want to mock.

Can we mock a class in C#?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.


2 Answers

Yep. Just pass in the parameters in your StrictMock() call:

// New FruitBasket that can hold 50 fruits. MockRepository mocks = new MockRepository(); FruitBasket basket = mocks.StrictMock<FruitBasket>(50); 
like image 191
John Feminella Avatar answered Oct 07 '22 22:10

John Feminella


If you Mock a concrete class without an empty/default constructor, then Rhino Mocks is going to have to use whatever other constructors are available. Rhino is going to need you to supply the parameters for any non-empty constructors since it won't have any clue how to build them otherwise.

My mistake is that I was attempting to pass nulls to the CreateMock or GenerateMock call, as soon as I generated a a non-null parameter for the constructor, the calls to create the mock or stub began working.

like image 38
Mark Rogers Avatar answered Oct 07 '22 22:10

Mark Rogers