rumi
rumi

Reputation: 3298

How to setup a controller's method using moq

I have an action method in my controller as below

public ActionResult Index()
{
     var supplier = GetSupplierForUser();
     var model = SupplierService.GetOutstandingItems(supplier);          
     return View(model);
}

I've setup the supplier service method as

var supplierService = new Mock<ISupplierService>();
var supplier = new Supplier { Name = "Some Name",Id = 100};

supplierService.Setup(s => s.GetOutstandingItems(supplier))
                            .Returns(outstandingSupplierItemInfo.Object);

I don't know how can we setup the method Supplier GetSupplierForUser() which is present in the base controller to return a Supplier object. From the moq setup above a null supplier is always passed to SupplierService.GetOutstandingItems(supplier)

Any ideas? thanks

Upvotes: 1

Views: 683

Answers (1)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

Maybe you need:

supplierService.Setup(s => s.GetOutstandingItems(It.IsAny<Supplier>()))
    .Returns(outstandingSupplierItemInfo.Object);

The It.IsAny<> stuff will make your Setup match any incoming object (argument).

Since you use a loose mock, if no Setup matches the arguemnts in question, Moq will just return null. Consider using MockBehavior.Strict to have an exception instead.

If you do not use It.IsAny<>, Moq will have to try to see if the supplier that is passed to Moq, "is equal to" the supplier you used when you made the Setup. Here it can become important what .Equals(...) semantics your type (class or struct) Supplier has.

If you do not have the relevant Equals semantics, but still want to restrict the Setup to a particular situation, try this instead:

supplierService
    .Setup(s => s.GetOutstandingItems(It.Is((Supplier s) => s.Name == "Some Name" && s.Id == 100)))
    .Returns(outstandingSupplierItemInfo.Object);

Upvotes: 2

Related Questions