SharePoint Newbie
SharePoint Newbie

Reputation: 6082

Cannot mock class with constructor having array parameter using Rhino Mocks

We are not able to mock this 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,

Upvotes: 5

Views: 4332

Answers (2)

Jimmy Lyke
Jimmy Lyke

Reputation: 330

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(...);
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

Try like this:

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

Upvotes: 6

Related Questions