简体   繁体   English

如何为方法生成单元测试代码

[英]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: 一些标准的最佳实践:

  • put all your tests in a tests folder at the root of your project. 将所有测试放在项目根目录下的tests文件夹中。
  • write one test module for each python module you're testing. 为你正在测试的每个python模块编写一个测试模块。
  • test modules should start with the word test . 测试模块应该从单词test开始。
  • test methods should start with the word 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感到满意时(并且它不需要很长时间),它有一些很好的扩展,当你的测试数量和范围增加时,它将使生活更轻松:

  • nose -- easily find and run all your tests, and more. 鼻子 - 轻松找到并运行所有测试等等。
  • testoob -- colorized output (and more, but that's why I use it). testoob - 彩色输出(以及更多,但这就是我使用它的原因)。
  • pythoscope -- haven't tried it, but this will automatically generate (failing) test stubs for your application. pythoscope - 没有尝试过,但这会自动为您的应用程序生成(失败)测试存根。 Should save a lot of time writing boilerplate code. 应该节省大量编写样板代码的时间。

这是一个例子 ,您可能想要阅读有关pythons单元测试的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM