Edg*_*rka 1 java junit unit-testing
我刚刚开始使用 junit/单元测试工具。现在我感受到了它的好处 :) 如果 junit 测试失败,是否可以打印字段值?
\n\n我的方法尝试实现 INT(A(D \xe2\x80\x94 B)^C):
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}\nRun Code Online (Sandbox Code Playgroud)\n\n我的测试:
\n\npublic void testCountlongJumpEventPoints(){\n PointsCountingTableRow row = Tables.get2001table().getLongJump();\n float cm = 736f;\n assertEquals(900,PointCounterService.countFieldEventPoints(row,cm));\n}\nRun Code Online (Sandbox Code Playgroud)\n\n控制台打印:
\n\njava.lang.AssertionError: \nExpected :900\nActual :901\nRun Code Online (Sandbox Code Playgroud)\n\n向上取整的方法(我感觉有问题):
\n\nprivate static int roundUP(double floatNumber){\n return (int) Math.round(floatNumber + .5);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n行类:
\n\npublic 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}\nRun Code Online (Sandbox Code Playgroud)\n\n}
\n欢迎来到单元测试的美妙世界 :) 为了代码覆盖,最好为 API 中的每个公共方法编写一组测试方法:每个有趣的案例一个,包括成功和失败的测试(感谢弗洛里安·沙茨)。
那么,使用私有方法 (as )该怎么办roundUP?它们还值得拥有一个测试电池,您可以在对 API 进行简单重构后轻松设计:
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)