Reputation: 9963
I am trying to get my head around moq and mvc. I have setup a moq and added a valid Setup to it.
My test to call my interface.
var id = 2;
var customer = new Customer()
{
CustomerId = 2,
FirstName = "Tomas",
LastName = "Smith"
};
var moq = new Mock<ICustomerRepository>();
moq.Setup(x => x.Find(id, 1234))
.Returns(Task.FromResult(customer));
var controller = new MyController(moq.Object);
var result = await controller.Get(id);
Now within my Get action I call my repository to get in this case a customer. However I need to pass in an extra parameter which is an int
var customer = await _repository.FindAsync(customerid, GetSourceId());
How can I moq GetSourceId() to return an int? without actually needing to call the method which I know will fail as its pulling data from the request header?
Upvotes: 0
Views: 1634
Reputation: 1907
var getSource = Mock<IYourInterfaceHere>();
getSource.Setup(x => x.GetSource(YourParams)).Returns(1);
With Moq, if you are going to call your Get method, you will need to check all the methods that use this Get method in the call, and mock all of them, for example:
Your Get method inside, call a GetSource() and GetSource() inside, call another method called GetId(), then if you are trying to test your Get method, you will need to mock your GetSource() and your GetId() too. Like a cascade.
Upvotes: 0
Reputation: 50728
If GetSourceId() is a method on the controller, you would have to mock the constructor via:
// mock takes params of constructor args
var ctlr = new Mock(Of MyController)(moq.Object);
ctlr.Setup(i => i.GetSourceId()).Returns(5);
var obj = ctlr.Object;
var result = obj.Get();
I was able to then call the action method directly on the mock, and it invoked the logic for me; I didn't need to do an explicit setup on the mock to call the original method.
Upvotes: 1