Andy
Andy

Reputation: 5268

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

Upvotes: 6

Views: 457

Answers (1)

cdhowie
cdhowie

Reputation: 168988

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

Upvotes: 8

Related Questions