[英]how to generate unit test code for methods
i want to write code for unit test to test my application code. 我想编写单元测试代码来测试我的应用程序代码。 I have different methods and now want to test these methods one by one in python script. 我有不同的方法,现在想在python脚本中逐个测试这些方法。 but i do not how to i write. 但我不怎么写。 can any one give me example of small code for unit testing in python. 任何人都可以给我一些python中单元测试的小代码示例。 i am thankful 我很感激
Read the unit testing framework section of the Python Library Reference . 阅读Python Library Reference的单元测试框架部分 。
A basic example from the documentation: 文档中的基本示例 :
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def testshuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def testchoice(self):
element = random.choice(self.seq)
self.assert_(element in self.seq)
def testsample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assert_(element in self.seq)
if __name__ == '__main__':
unittest.main()
It's probably best to start off with the given unittest
example. 最好从给定的unittest
示例开始。 Some standard best practices: 一些标准的最佳实践:
tests
folder at the root of your project. 将所有测试放在项目根目录下的tests
文件夹中。 test
. 测试模块应该从单词test
开始。 test
. 测试方法应该从单词test
开始。 When you've become comfortable with unittest
(and it shouldn't take long), there are some nice extensions to it that will make life easier as your tests grow in number and scope: 当你对unittest
感到满意时(并且它不需要很长时间),它有一些很好的扩展,当你的测试数量和范围增加时,它将使生活更轻松:
这是一个例子 ,您可能想要阅读有关pythons单元测试的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.