views:

199

answers:

2

Hi,

We cannot mock his class in RhinoMocks.

public class Service
{
    public Service(Command[] commands){}
}
public abstract class Command {}

// Code
var mock = MockRepository.GenerateMock<Service>(new Command[]{}); // or
mock = MockRepository.GenerateMock<Service>(null)

Rhino mocks fails complaining that it cannot find a constructor with matching arguments. What am I doing wrong?

Thanks,

+3  A: 

Try like this:

var mock = MockRepository.GenerateMock<Service>(
    new object[] { new Command[0] }
);
Darin Dimitrov
A: 

Additionally, you could wrap Service with an interface and not worry about the constructor arguments. If the constructor ever changes -- your tests will be tied to those implementation details and need to be updated.

var mock = MockRepository.GenerateMock<IService>();

Edit: At least isolate the creation of that Mock so if your constructor on Service changes, you won't have to update in every single place. A common practice is as follows:

(in your test class)

private ObjectWithServiceDependency CreateObjectUnderTest(){
     //Here you would inject your Service dependency with the above answer from Darin
     //i.e.
     var mockService= MockRepository.GenerateMock<Service>(new object[] {new Command[0] });
     var objectUnderTest = new ObjectWithServiceDependency(mockService);
     return objectUnderTest;
}

Then in a test,

[Test]
public TestSomething(){
     var out = CreateObjectUnderTest();
     //do testing
     mockService.Expect(...);
}
Jimmy Lyke
Don't want to do this. :(
SharePoint Newbie
I'm not the biggest fan of interfaces for the sake of mocking. However, you will have technical debt tied to the tests knowing about the constructor's parameters and type. I'll edit my example to show a good practice for at least isolating the places that will need to change if the constructor needed to change.
Jimmy Lyke