Cannot mock class with constructor having array parameter using Rhino Mocks

折月煮酒 提交于 2019-12-23 10:28:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!