Moq confusion - Setup() v Setup<>()

丶灬走出姿态 提交于 2019-12-12 10:46:49

问题


I have a mock being created like this:

var mock = new Mock<IPacket>(MockBehavior.Strict);
mock.Setup(p => p.GetBytes()).Returns(new byte[] { }).Verifiable();

The intellisense for the Setup method says this:

"Specifies a setup on the mocked type for a call to a void returning method."

But the mocked method p.GetBytes() does not return void, it returns a byte array.

Alternatively another Setup method is defined as Setup<>, and I can create my mock like this:

var mock = new Mock<IPacket>(MockBehavior.Strict);
mock.Setup<byte[]>(p => p.GetBytes()).Returns(new byte[] { }).Verifiable();

The intellisense of this Setup method states:

"Specifies a setup on the mocked type for a call to a value returning method."

.
.
Whichever method I choose, it compiles and tests OK. So, I'm confused as to which way I should be doing this. What is the difference between .Setup() and .Setup<>(), and am I doing it right?

The docs for Moq are somewhat lacking, shall we say. :)


回答1:


The compiler is inferring from the lambda passed to Setup() that you meant to call the generic version, and so it happily infers the generic argument for you. If you use Reflector you will see that the first code example is in fact calling Setup<byte[]>().



来源:https://stackoverflow.com/questions/6767446/moq-confusion-setup-v-setup

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