Kinexus
Kinexus

Reputation: 12904

Mocking Interface using Moq - never hits the mocked method

I am attempting to setup a simple unit test for my code. I have an interface and implementation that talks to an external service via WCF. I am attempting to mock this with the code below;

private Mock<IPayments> _mockIPayments;

_mockIPayments.Setup(x => x.GetCreditCard(It.IsAny<GetCreditCardRequest>())).Returns(getCreditCardResponse);

In the unit test itself, I create an instance of the service that would ultimately call the WCF service;

var paymentService = new PaymentService();

var response = paymentService.GetCardDetails(cardId);

Within the PaymentService itself, the code;

var response = ServiceInvoker.Invoke<IPayments, GetCreditCardRequest, GetCreditCardResponse>
                          (
                              "Payments",
                              request,
                              (proxy, req) => proxy.GetCreditCard(req));

(Note that ServiceInvoker.Invoke is just a wrapper to create a channel and process the request)

Am I missing something, should the mock setup not be catching the request to GetCreditCard?

ETA

To make it a little clearer, the flow is;

UnitTest -> PaymentsService -> IPayments

Upvotes: 2

Views: 1457

Answers (2)

Gilles
Gilles

Reputation: 5417

Simply specifying a setup will not let Moq replace all instances of some interface with the what you specified. It simply defines what Moq will return when a certain Mock instance will be called. In your case _mockIPayments.

You then have to use that mocked IPayments instance in your code (either pass it in a constructor or method) for your code to actually use it.

If your PaymentService is currently creating an IPayments object internally, to use mocking you will have to use something like Dependency Injection so that you are able to specify the IPayments instance externally and thus supply a mock instance in your tests.

Likewise:

var paymentService = new PaymentService(_mockIPayments.Object);

Upvotes: 0

the_joric
the_joric

Reputation: 12261

You need to pass your mocked instance to the service somehow.

var paymentService = new PaymentService(_mockIPayments.Object);

Upvotes: 2

Related Questions