如果 junit 测试失败,是否可以打印字段值?

Edg*_*rka 1 java junit unit-testing

我刚刚开始使用 junit/单元测试工具。现在我感受到了它的好处 :) 如果 junit 测试失败,是否可以打印字段值?

\n\n

我的方法尝试实现 INT(A(D \xe2\x80\x94 B)^C):

\n\n
public static int countFieldEventPoints(PointsCountingTableRow row,float centimetres){\n    float temp = row.getA()*(float)Math.pow((centimetres - row.getB()),row.getC());\n    return roundUP(temp);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的测试:

\n\n
public void testCountlongJumpEventPoints(){\n    PointsCountingTableRow row = Tables.get2001table().getLongJump();\n    float cm = 736f;\n    assertEquals(900,PointCounterService.countFieldEventPoints(row,cm));\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

控制台打印:

\n\n
java.lang.AssertionError: \nExpected :900\nActual   :901\n
Run Code Online (Sandbox Code Playgroud)\n\n

向上取整的方法(我感觉有问题):

\n\n
private static int roundUP(double floatNumber){\n    return (int) Math.round(floatNumber + .5);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

行类:

\n\n
public class PointsCountingTableRow {\nprivate float A;\nprivate float B;\nprivate float C;\n\n\npublic PointsCountingTableRow(float a, float b, float c) {\n    A = a;\n    B = b;\n    C = c;\n}\n\npublic float getA() {\n    return A;\n}\n\npublic float getB() {\n    return B;\n}\n\npublic float getC() {\n    return C;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

}

\n

Lit*_*nti 5

欢迎来到单元测试的美妙世界 :) 为了代码覆盖,最好为 API 中的每个公共方法编写一组测试方法:每个有趣的案例一个,包括成功和失败的测试(感谢弗洛里安·沙茨)。

那么,使用私有方法 (as )该怎么办roundUP?它们还值得拥有一个测试电池,您可以在对 API 进行简单重构后轻松设计:

  • 创建一个具有包(默认)访问权限的新“helper”类和一个私有构造函数。这个类将只包含公共静态方法。
  • 从其实际容器类移至roundUP辅助类,并将其公开。
  • 在同一个包中创建一个公共测试器类(从而授予它对帮助器类的访问权限),并使用必要的测试方法来填充它。

回到您的案例,您可以编写几种测试方法来roundUP正确进行基准测试:我建议十种方法:roundUP(0.0), roundUP(0.1), roundUP(0.2)... roundUP(0.9)

作为测试驱动开发的一部分,每次报告程序中的新错误时,您必须编写新的测试器方法来重现此类错误。然后,修复错误,直到所有测试器工作正常(新的和现有的):通过这种方式,测试电池将会增长,并确保没有更新或修复会意外破坏现有行为。


如果测试失败,是否可以打印行字段值?

当然。您可以对测试方法进行编程,以便在失败时做出反应,如下所示:

@Test
public void myTest()
{
    // Prepare the input parameters:
    PointsCountingTableRow row=...
    float centimetres=...

    // Perform the test:
    int result=countFieldEventPoints(row, centimeters);

    // Check the results:
    String messageInCaseOfFail="row="+row.toString();
    assertEquals(messageInCaseOfFail, expectedResult, result);
}
Run Code Online (Sandbox Code Playgroud)

或者也可以通过fail以下方法:

@Test
public void myTest()
{
    // Prepare the input parameters:
    ...

    // Perform the test:
    try
    {
       int result=countFieldEventPoints(row, centimeters);
       // Check the results:
       assert...
    }
    catch (SomeException e)
    {
        fail(messsageInCaseOfFail);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 每个公共方法都进行一次测试?听起来很奇怪,我会为每个公共方法中的每个分支编写一个测试。例如,如果我的方法应该针对某个无效参数引发异常,我会为此创建一个测试方法。如果它应该为某个有效参数返回某个结果,我会为此编写一个测试方法,等等。 (2认同)