我不太擅长“单元测试”主题。我想创建一个单元测试,以便说“嘿, body ,这是错误(或正确)的答案,因为 blabla!”。我需要进行单元测试,因为我花了 3 MF 周才找到机器学习模型中的预测不起作用的原因!因此我希望将来避免出现此类错误。
问题:
- 当
len(X) - len(pred_values)
不等于num_step
时,如何让代码提醒我? - 我是否需要创建一个单元测试文件来收集所有单元测试,例如
unittest.py
? - 我们需要将单元测试远离主代码吗?
最佳答案
1.
测试代码可以通过断言的方式提醒您。在您的测试中,您可以使用 self.assertEqual()
self.assertEqual(len(X) - len(pred_values), num_step)
2.
是的,您通常会收集您的TestCase
模块中前缀为 test_
的类。因此,如果被测试的代码位于名为 foo.py
的模块中,您可以将测试放在 test_foo.py
中。
test_foo.py
内您可以创建多个TestCase
将相关测试分组在一起的类。
3. 将测试与主代码分开是个好主意,尽管不是强制性的。您可能想要分开测试的原因包括(如文档中引用的):
- The test module can be run standalone from the command line.
- The test code can more easily be separated from shipped code.
- There is less temptation to change test code to fit the code it tests without a good reason.
- Test code should be modified much less frequently than the code it tests.
- Tested code can be refactored more easily.
- Tests for modules written in C must be in separate modules anyway, so why not be consistent?
- If the testing strategy changes, there is no need to change the source code.
更多信息请参见 official docs .
关于unit-testing - 如果不等于真实值 num_steps 则发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271564/