Ruby 测试、调试与常见问题处理
1. 测试用例的组织与运行
在 Ruby 中,目前展示的测试用例都是可运行的 Test::Unit
程序。例如,若 Roman
类的测试用例存于 test_roman.rb
文件中,可通过以下命令从命令行运行测试:
% ruby test_roman.rb
Loaded suite test_roman
Started
..
Finished in 0.039257 seconds.
2 tests, 9 assertions, 0 failures, 0 errors
Test::Unit
很智能,能察觉没有主程序,进而收集所有测试用例类并依次运行。若想仅运行特定的测试方法,可使用如下命令:
% ruby test_roman.rb --name test_range
Loaded suite test_roman
Started
.
Finished in 0.006445 seconds.
1 tests, 4 assertions, 0 failures, 0 errors
2. 测试文件的存放位置
开展单元测试时,产生的测试代码量可能与生产代码量相近,所以需考虑测试文件的存放位置。若将测试文件与常规生产代码源文件放在一起,目录会变得臃肿,实际上每个生产源文件会对应两个文件。
常见的解决