Reputation: 373
I'm teaching myself moq
testing and was wondering what I'm doing wrong in this instance.
I'm unsure of what to include in the return type. I know by including a value in there e.g 4 then this will ignore the parameters inside of the MulitplyValues(2,2)
call and set response.basepremium
to 4.
I want to test the MultiplyValues
method is working and passes the test based on the parameter values. What am I doing incorrectly? Any help would be appreciated
I have now changed my test to the following that fits in with replies. Is this correct?
[Test]
public void MoqTestFindTax()
{
Mock<IPremiumResponse> premiumresponse = new Mock<IPremiumResponse>();
CalculateTax calcualtetax = new CalculateTax(premiumresponse.Object);
decimal i = 0.648m;
decimal totalsofar = 12.96m;
decimal tax = 0.05m;
premiumresponse
.Setup(x => x.MulitplyValues(It.IsAny<decimal>(), It.IsAny<decimal>())).Returns(i);
Assert.AreEqual(13.61, calcualtetax.FindTaxTotal(totalsofar, tax));
}
Then I have created a tax calculator class
public class CalculateTax
{
IPremiumResponse _response;
public CalculateTax(IPremiumResponse premiumresponse)
{
_response = premiumresponse;
}
public decimal FindTaxTotal(decimal val1, decimal val2)
{
return _response.MulitplyValues(val1,val2) + val1;
}
}
}
Upvotes: 0
Views: 1183
Reputation: 6238
You don't need a Mock at all, you should be testing the implementation directly:
PremiumResponse response = new PremiumResponse();
Assert.AreEqual(4, response.MultiplyValues(2, 2));
You would use a mock of an interface when you are testing a different section of code that depends on that interface. The purpose would be to have predictable return values so that you can properly formulate your expectations, and to prevent any potential bugs in one area of your code from affecting the unit test results for another.
For example, say you had another class, Foo
:
public class Foo
{
private IPremiumResponse _premiumResponse;
public Foo(IPremiumResponse premiumResponse)
{
_premiumResponse = premiumResponse;
}
public int DoSomeMathThenAddOne(int n)
{
return _premiumResponse.MultiplyValues(n, n) + 1;
}
}
You would only want to test the "+ 1" functionality of DoSomeMathThenAddOne
, since the multiplication unit is elsewhere. (A lame example, I know.) The unit test might look something like this:
Mock<IPremiumResponse> premiumresponse = new Mock<IPremiumResponse>();
Foo foo = new Foo(premiumresponse.Object);
premiumresponse.Setup(x => x.MulitplyValues(It.IsAny<decimal>(), It.IsAny<decimal>())).Returns(4);
Assert.AreEqual(5, foo.DoSomeMathThenAddOne(2));
Upvotes: 1
Reputation: 15875
If you want to test MultipleValues
method then you dont want to mock it. You want to mock the parts that pull your focus away from MulitpleValues
, but not the method it self.
PremiumResponse response = new PremiumResponse();
var value = response.MultiplyValues(2, 2)
Assert.AreEqual(4, value);
Upvotes: 0