如何使用Mock.Of< T>()模拟没有默认构造函数的类?

问题描述:

使用起订量,我需要为现有的具有没有默认ctor (不是界面*)创建一个伪造品.

Using Moq, I need to create a fake over an existing class (not interface*) that has no default ctor.

我可以使用传统"语法来做到这一点:

I can do this using the "traditional" syntax:

var fakeResponsePacket = new Mock<DataResponse>(
    new object[]{0, 0, 0, new byte[0]}); //specify ctor arguments

fakeResponsePacket.Setup(p => p.DataLength).Returns(5);

var checkResult = sut.Check(fakeResponsePacket.Object);

我的问题是:是否可以使用较新的Mock.Of<T>()语法执行相同的操作?

My question is: Is there a way to do the same using the newer Mock.Of<T>() syntax ?

据我所见,Mock.Of<T>只有两个重载,没有一个接受参数:

From what I can see, there are only two overloads for Mock.Of<T>, none of which accept arguments:

//1 no params at all
var fakeResponsePacket = Mock.Of<DataResponse>(/*??*/);
fakeResponsePacket.DataLength = 5;

//2 the touted 'linq to Moq'
var fakeResponsePacket = Mock.Of<DataResponse>(/*??*/
    p => p.DataLength == 5
);

var checkResult = sut.Check(fakeResponsePacket);

-
*我想要使用界面.但是后来发生了现实.我们不要讨论它.

--
* I wanted to use an interface. But then reality happened. Let's not go into it.

不,似乎没有办法.

旁注:在旧"语法中,您可以编写:

Side-remark: In the "old" syntax, you can just write:

new Mock<DataResponse>(0, 0, 0, new byte[0]) //specify ctor arguments

因为数组参数为params(参数数组).

since the array parameter there is params (a parameter array).

要解决将0转换为MockBehavior的问题(请参见上面的注释和划掉的文字),您可以执行以下操作:

To get around the issue with 0 being converted to a MockBehavior (see comments and crossed out text above), you could either do:

new Mock<DataResponse>(MockBehavior.Loose, 0, 0, 0, new byte[0]) //specify ctor arguments

或这样做:

var v = 0; // this v cannot be const!
// ...
new Mock<DataResponse>(v, 0, 0, new byte[0]) //specify ctor arguments

但这当然不是您要问的部分.

but this is not really part of what you ask, of course.