简体   繁体   中英

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,

Try like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM