简体   繁体   English

如何使用unittest在Python中编写测试

[英]How to write tests in Python using unittest

I want to write my library in TDD methodology, but I have no idea how to design directory structure (or how to use unittest ). 我想用TDD方法编写我的库,但是我不知道如何设计目录结构(或如何使用unittest )。 Now I create a directory tree such as: 现在,我创建一个目录树,例如:

myproject (directory)
    - tests (directory)
    - src (directory)
    - test.py (file running tests)

Each class from src has its own unittest class. src每个类都有其自己的unittest类。 Each directory has its own __init__.py file. 每个目录都有其自己的__init__.py文件。 I want to run tests only from test.py file and thanks to this each test can from src.modulename import classname and than runs test unittest.main() function. 我只想从test.py文件运行测试,并且由于此,每个测试都可以from src.modulename import classname然后运行test unittest.main()函数。 Unfortunately it doesn't work (runs zero tests). 不幸的是,它不起作用(运行零测试)。

Is this good approach? 这是好方法吗? What are my mistakes? 我有什么错

The code in file test.py should look like: 文件test.py的代码应类似于:

from tests import *
import unittest

if __name__ == '__main__':
    testsuite = unittest.TestLoader().discover('.')
    unittest.TextTestRunner(verbosity=1).run(testsuite)

This code copies all tests from tests directory, because it copies entire package. 此代码从tests目录复制所有测试,因为它复制了整个程序包。 The main method runs all test methods included in tests package's classes. main方法运行tests包类中包含的所有测试方法。 Each test file name must start with test . 每个测试文件名都必须以test开头。

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

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