Reputation: 15807
Please see the code below:
mockBusinessLayer.Setup(m => m.Calculate(It.IsAny<integer>(), It.IsAny<integer>())).Callback
(() => mockBusinessLayer.SetupGet(y => y.FirstNumber).Returns(Helper.FirstNumber));
mockBusinessLayer.Setup(m => m.Calculate(It.IsAny<integer>(), It.IsAny<integer>())).Callback
(() => mockBusinessLayer.SetupGet(y => y.SecondNumber).Returns(Helper.SecondNumber));
Calculate() accepts two integers and adds them together. How do I setup multiple SetupGets on the same mock object? The above code only sets up the Get callback on SecondNumber (because it is the last time SetupGet is called).
Update
This is the function I am trying to test:
public CalculatorDTO Calculate(int NumberOne, int NumberTwo)
{
_Calculator.Calculate(NumberOne, NumberTwo);
return Mapper.Map<CalculatorDTO>(_changeCalculator);
}
}
Is it better to do this:
mockBusinessLayer.Setup(x => x.FirstNumber).Returns(Helper.FirstNumber); mockBusinessLayer.Setup(x => x.SecondNumber).Returns(Helper.SecondNumber);
Upvotes: 0
Views: 754
Reputation: 23747
You say:
The above code only sets up the Get callback on SecondNumber (because it is the last time SetupGet is called).
But that's not quite right: your calls to Setup
of Calculate
are identical and thus the second one overrides the first. It's as if the first Setup
never occurred.
Putting the calls to SetupGet
in the Callback
is unnecessary and confusing. I'd set it up like this:
mockBusinessLayer.SetupGet(y => y.FirstNumber).Returns(Helper.FirstNumber)
mockBusinessLayer.SetupGet(y => y.SecondNumber).Returns(Helper.SecondNumber)
mockBusinessLayer.Setup(m => m.Calculate(It.IsAny<integer>(), It.IsAny<integer>()));
Any time FirstNumber
is gotten, it will return Helper.FirstNumber
, and likewise for SecondNumber
returning Helper.SecondNumber
.
All that being said, without more of your code (What type is _Calculator
? Does your mockBusinessLayer
really expose FirstNumber
/SecondNumber
and Calculate
?) it's hard to offer more complete steps to move forward. For instance, you don't show the setup of your Mapper.Map
method, which you'll need if you want to test this method.
In response to your update...
SetupGet
offers a slightly cleaner API: you're required to pass a Func
, while Setup
will allow you to pass an Action
; it returns a slightly more restricted ISetupGet
interface. SetupGet
also has better semantics, indicating to readers that you intend to set up only the get.
In the Moq source they actually boil down to the same code so either get the job done just as well.
Upvotes: 2