Reputation: 131
I have following code, and willing to do Moq testing for DoDivision method of DoMath class, I need to test successful and unsuccessful case(i.e. divide by zero). So, how I should create Moq object of Math class and pass it to DoDivision and make assert on output?
public interface IMath
{
void Divide(int firstNumber, int secondNumber, Action<double> callback, Action<string> errorCallback);
}
public class Math : IMath
{
public void Divide(int firstNumber, int secondNumber, Action<double> callback, Action<string> errorCallback)
{
if (secondNumber == 0)
{
errorCallback("Arithmetic exception: Division by zero is not allowed.");
}
else
{
callback(firstNumber / secondNumber);
}
}
}
public class DoMaths
{
public IMath math;
public void DoDivision(int firstNumber, int secondNumber, Action<string> callback, Action<string> errorCallback)
{
math.Divide(firstNumber, secondNumber, ans =>
{
callback(String.Format("{0} / {1} = {2}", firstNumber, secondNumber, ans.ToString()));
}, error =>
{
errorCallback(error);
});
}
}
DoMaths doMaths = new DoMaths();
doMaths.math = new Math.Math();
doMaths.DoDivision(2, 0, ans =>
{
Console.WriteLine(ans);
}, error => {
Console.WriteLine(error);
});
Upvotes: 1
Views: 1201
Reputation: 131
I solved this case, got help from "hSchroedl" comment. I am publishing mine solution code, so some one can have help in such case.
const int firstNumberParam = 2;
const int secondNumberParam = 1;
var mathMoq = new Moq.Mock<Math.IMath>();
mathMoq.Setup(m => m.Divide(
It.IsAny<int>(), It.IsAny<int>(), //secondNumberParam,
It.IsAny<Action<double>>(), It.IsAny<Action<string>>()
)).Callback<Int32, Int32, Action<double>, Action<string>>((firstNumber, secondNumber, successCallback, errorCallback) =>
{
successCallback(firstNumberParam);
errorCallback("Arithmetic exception: Division by zero is not allowed.");
});
DoMaths doMaths = new DoMaths();
doMaths.math = mathMoq.Object;
doMaths.DoDivision(firstNumberParam, secondNumberParam, success =>
{
Assert.AreEqual("2 / 1 = 2", success);
}, error =>
{
Assert.AreEqual("Arithmetic exception: Division by zero is not allowed.", error);
});
Upvotes: 1