问题
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,
回答1:
Try like this:
var mock = MockRepository.GenerateMock<Service>(
new object[] { new Command[0] }
);
回答2:
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(...);
}
来源:https://stackoverflow.com/questions/2855271/cannot-mock-class-with-constructor-having-array-parameter-using-rhino-mocks