C# 最小起订量。测试具有多个动作参数的函数

C# Moq. testing for function having multiple action parameters

我有以下代码,愿意为 DoMath 的 DoDivision 方法做 Moq 测试 class,我需要测试成功和不成功的情况(即除以零)。那么,我应该如何创建 Math class 的 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);
});

我解决了这个问题,得到了 "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);
});