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?
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 .
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With