我有以下代码,并且愿意对DoMath类的DoDivision方法进行Moq测试,我需要测试成功和不成功的情况(即除以零)。那么,我应该如何创建Math类的Moq对象并将其传递给DoDivision并在输出中生成断言?
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);
});
答案 0 :(得分:2)
我解决了这个案子,得到了“hSchroedl”评论的帮助。我正在发布我的解决方案代码,所以有人可以在这种情况下提供帮助。
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);
});