Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. :)

like image 585
Andy Avatar asked Jul 20 '11 19:07

Andy


1 Answers

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[]>().

like image 149
cdhowie Avatar answered Nov 04 '22 06:11

cdhowie