C# 使用 RhinoMocks,如何在没有空构造函数的情况下模拟或存根具体类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1291085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:44:42  来源:igfitidea点击:

Using RhinoMocks, how do you mock or stub a concrete class without an empty constructor?

c#constructortddrhino-mocks

提问by Mark Rogers

Mocking a concrete class with Rhino Mocks seems to work pretty easy when you have an empty constructor on a class:

当类上有一个空的构造函数时,用 Rhino Mocks 模拟一个具体的类似乎很容易:

public class MyClass{
     public MyClass() {}
}

But if I add a constructor that takes parameters and remove the one that doesn't take parameters:

但是如果我添加一个带参数的构造函数并删除一个不带参数的构造函数:

public class MyClass{
     public MyClass(MyOtherClass instance) {}
}

I tend to get an exception:

我倾向于得到一个例外:

System.MissingMethodException : Can't find a constructor with matching arguments

System.MissingMethodException:找不到具有匹配参数的构造函数

I've tried putting in nulls in my call to Mock or Stub, but it doesn't work.

我试过在我对 Mock 或 Stub 的调用中放入空值,但它不起作用。

Can I create mocks and stubs of concrete classes that lack parameter-less constructors?

我可以创建缺少无参数构造函数的具体类的模拟和存根吗?

采纳答案by John Feminella

Yep. Just pass in the parameters in your StrictMock()call:

是的。只需在StrictMock()调用中传入参数:

// New FruitBasket that can hold 50 fruits.
MockRepository mocks = new MockRepository();
FruitBasket basket = mocks.StrictMock<FruitBasket>(50);

回答by womp

You have to pass them in after your DynamicMock<T>statement, which takes a parameter array as an argument. Unfortunately there's no type checking on it, but it will call the appropriate constructor if you match up your arguments to the signature.

您必须在您的DynamicMock<T>语句之后传递它们,该语句将参数数组作为参数。不幸的是,没有对其进行类型检查,但是如果您将参数与签名相匹配,它将调用适当的构造函数。

For example:

例如:

var myMock = MockRepository.DynamicMock<MyClassWithVirtuals>(int x, myObj y);

回答by Mark Rogers

If you Mock a concrete class without an empty/default constructor, then Rhino Mocks is going to have to use whatever other constructors are available. Rhino is going to need you to supply the parameters for any non-empty constructors since it won't have any clue how to build them otherwise.

如果你 Mock 一个没有空/默认构造函数的具体类,那么 Rhino Mocks 将不得不使用任何其他可用的构造函数。Rhino 将需要您为任何非空构造函数提供参数,因为它不知道如何构建它们。

My mistake is that I was attempting to pass nulls to the CreateMockor GenerateMockcall, as soon as I generated a a non-null parameter for the constructor, the calls to create the mock or stub began working.

我的错误是我试图将空值传递给CreateMockorGenerateMock调用,一旦我为构造函数生成了一个非空参数,创建模拟或存根的调用就开始工作。