本文介绍了如何使用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.

推荐答案

不,似乎没有办法.

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.

这篇关于如何使用Mock.Of&lt; T&gt;()模拟没有默认构造函数的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 01:55