28

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?

Mark Rogers
  • 96,497
  • 18
  • 85
  • 138

3 Answers3

32

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);
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
John Feminella
  • 303,634
  • 46
  • 339
  • 357
3

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.

Mark Rogers
  • 96,497
  • 18
  • 85
  • 138
1

You have to pass them in after your DynamicMock<T> statement, which takes a parameter array as an argument. Unfortunately there's no type checking on it, but it will call the appropriate constructor if you match up your arguments to the signature.

For example:

var myMock = MockRepository.DynamicMock<MyClassWithVirtuals>(int x, myObj y);
womp
  • 115,835
  • 26
  • 236
  • 269