无法使用 Rhino Mocks 模拟具有数组参数的构造函数的类

发布于 2024-09-02 14:31:45 字数 374 浏览 0 评论 0原文

我们无法在 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 模拟失败,抱怨它找不到具有匹配参数的构造函数。 我做错了什么?

谢谢,

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陪你搞怪i 2024-09-09 14:31:45

尝试这样:

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

Try like this:

var mock = MockRepository.GenerateMock<Service>(
    new object[] { new Command[0] }
);
花开半夏魅人心 2024-09-09 14:31:45

此外,您可以使用接口包装 Service,而不必担心构造函数参数。如果构造函数发生变化——您的测试将与这些实现细节相关联并且需要更新。

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

编辑:至少隔离该模拟的创建,这样如果服务上的构造函数发生更改,您就不必在每个地方进行更新。常见的做法如下:(

在您的测试类中)

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;
}

然后在测试中,

[Test]
public TestSomething(){
     var out = CreateObjectUnderTest();
     //do testing
     mockService.Expect(...);
}

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(...);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文