将可选消息参数添加到 assertEquals

Add optional message parameter to assertEquals

免责声明:我是 Haxe 的新手,但我有许多其他语言的经验。

我有类似以下的测试:

  function doTest(type:SomethingMagic, tests:Array<Array<Int>>) {
    for (t in tests) {
      var res = DoSomeMagicalWork(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
      assertEquals(type, res.type);
    }
  }

这个问题是单元测试框架,当 运行 在许多不同的数组上时,没有给我测试失败的正确行。换句话说,如果我 运行 将此方法与一堆数组结合使用,例如:

 doTest(SOME_MAGIC_TYPE,
    [[0, 0, 0, 1625, 0, 35, 0, 0, 0, 0, 0],
    ...
 ]);

并且这些行之一失败了,它没有告诉我 哪一行 失败了。现在,我知道我可能会重组这些测试,使其更直观一些,但这是别人写的,我现在没有能力更改每一个测试。

我想做的是:

  function doTest(type:SomethingMagic, tests:Array<Array<Int>>) {
    var number = 0;
    for (t in tests) {
      var res = DoSomeMagicalWork(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
      assertEquals(type, res.type, "Test #" + number + " for type " + type);
      number++;
    }
  }

所以,基本上,我希望能够将一些额外的消息传递信息传递给 assertEquals 函数,类似于在其他单元测试框架中可以做的事情。然后,在失败时,它会输出标准的断言消息,可能附加了我作为参数发送给函数的附加消息。最初,我认为它就像子类化一样简单 haxe.TestCase,但由于 Haxe 解释类型的方式(显然),这似乎并不像我想象的那么简单。

有没有人成功地完成了类似的事情,可以给我一个如何完成它的建议?

如果您只想获取错误的位置,您可以使用 haxe.PosInfos 作为 doTest() 函数的最后一个参数,并将该参数传递给 assertEquals(),如下所示:

import haxe.unit.TestCase;

class Main {
    static function main() {
        var r = new haxe.unit.TestRunner();
        r.add(new Test());
        r.run();
    }
}

class Test extends TestCase {
    public function new() {
        super();
    }

    public function testExample() {
        doTest(1, 1);
        doTest(1, 2);
        doTest(3, 3);
    }

    function doTest(a:Int, b:Int, ?pos:haxe.PosInfos) {
        assertEquals(a, b, pos);
    }
}

Online example here

它会给你错误中调用doTest()的位置:

Test::testExample() ERR: Main.hx:18(Test.testExample) - expected '1' but was '2'

如果要添加自定义消息,另一种选择是捕获 assertEquals() 错误并使用如下自定义错误重新抛出 currentTest

import haxe.unit.TestCase;

class Main {
    static function main() {
        var r = new haxe.unit.TestRunner();
        r.add(new Test());
        r.run();
    }
}

class Test extends TestCase {
    public function new() {
        super();
    }

    public function testExample() {
        doTest(1, 1, "Error on test 1");
        doTest(1, 2, "Error on test 2");
        doTest(3, 3, "Error on test 3");
    }

    function doTest(a:Int, b:Int, errorMsg:String, ?pos:haxe.PosInfos) {
        try {
            assertEquals(a, b, pos);   
        } catch(e:Dynamic) {
            currentTest.error = errorMsg;
            throw currentTest;
        }

    }
}

Online example here

这会给你以下错误:

Test::testExample() ERR: Main.hx:18(Test.testExample) - Error on test 2

您正在有效地将多个测试混合到一个测试中。而且 Haxe 无法告诉您数组元素的定义位置(行号等)

我的建议是更改 doTest 的签名以接受 Array<Int> 而不是 Array<Array<Int>> 并多次调用 doTest 而不是一次。结合 Justo 的建议,将 pos 对象传递给 assetEquals,您将正确获得位置。