views:

1161

answers:

3

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 or stubs of concrete classes with Rhino Mocks, or must I always supply (implicitly or explicitly) a parameter-less constructor?

+8  A: 

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

// New FruitBasket that can hold 50 fruits.
MockRepository mocks = new MockRepository();
FruitBasket basket = mocks.CreateMock<FruitBasket>(50);
John Feminella
A: 

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
A: 

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