Lucas Valle
Lucas Valle

Reputation: 33

Moq object always returns null , why?

I make the next moq call:

var mock = new Mock<IPagoService>();
mock.Setup(m => m.GetCodigoAutorizacion(Guid.NewGuid())).Returns("e");
string p = mock.Object.GetCodigoAutorizacion(Guid.NewGuid());

Why is the variable p null?

Upvotes: 1

Views: 458

Answers (4)

Julian
Julian

Reputation: 36710

When you have:

mock.Setup(m => m.GetCodigoAutorizacion("A")).Returns("B");

You will tell, if invoked with "A", then return "B". Note, If invoked with something else, e.g, "C", it returns the default value of the type.

So you need, if invoked with any then GUID returns "e" - you could use It.IsAny<T>().

So for this case:

mock.Setup(m => m.GetCodigoAutorizacion(It.IsAny<Guid>())).Returns("e");

Upvotes: 4

Ernestas Romeika
Ernestas Romeika

Reputation: 171

It's because the two Guid.NewGuid() calls generate two different guid values, and so when you're calling the mockup you're passing and entirely new guid from the one that was set up. You can either save the initial guid value and reuse it, or if you don't mind what guid it is you can use:
It.IsAny<Guid>() in the setup to accept any guid.

Upvotes: 0

juharr
juharr

Reputation: 32266

You're setup is using one Guid and the call another. Since the setup and the call do not match it returns the default. Instead assign the Guid to a variable and use that.

var mock = new Mock<IPagoService>();
var id = Guid.NewGuid();
mock.Setup(m => m.GetCodigoAutorizacion(id)).Returns("e");
string p = mock.Object.GetCodigoAutorizacion(id);

If you need to handle any Guid then do this instead

mock.Setup(m => m.GetCodigoAutorizacion(It.IsAny<Guid>())).Returns("e");

Upvotes: 2

Vidmantas Blazevicius
Vidmantas Blazevicius

Reputation: 4802

Guid.NewGuid() value will be different each time so it doesn’t satisfy your setup condition.

You can use Guid.Empty or some constant value to make this work.

Upvotes: 0

Related Questions