Python单元测试:在另一个模块中运行测试

bgu*_*ach 13 python tdd unit-testing module

我想将我的应用程序的文件放在文件夹/ Files下,而/ UnitTests中的测试单元,这样我就可以清楚地分开app和test了.

为了能够使用与mainApp.py相同的模块路由,我在根文件夹中创建了一个testController.py.

mainApp.py
testController.py
Files
  |__init__.py
  |Controllers
     | blabla.py
  | ...
UnitTests
  |__init__.py
  |test_something.py
Run Code Online (Sandbox Code Playgroud)

因此,如果在test_something.py中我想测试/Files/Controllers/blabla.py中的一个函数,我尝试以下方法:

import unittest
import Files.Controllers.blabla as blabla


class TestMyUnit(unittest.TestCase):

    def test_stupid(self):
        self.assertTrue(blabla.some_function())


if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)


然后从文件testController.py中,我执行以下代码:

import TestUnits.test_something as my_test
my_test.unittest.main()
Run Code Online (Sandbox Code Playgroud)

哪个输出没有失败,但没有执行测试

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
[Finished in 0.3s]
Run Code Online (Sandbox Code Playgroud)


我尝试过一个没有依赖关系的测试,如果执行" main "工作,但是当从外部调用时,输出相同的:

import unittest


def tested_unit():
    return True


class TestMyUnit(unittest.TestCase):

    def test_stupid(self):
        self.assertTrue(tested_unit())


if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

问题:我如何让这个工作?

rpa*_*ent 19

方法unittest.main()查看上下文中存在的所有unittest.TestCase类.因此,您只需要在testController.py文件中导入测试类,并在此文件的上下文中调用unittest.main().

所以你的文件testController.py应该是这样的:

import unittest    
from UnitTests.test_something import *
unittest.main()
Run Code Online (Sandbox Code Playgroud)

  • 好我编辑了我的答案来修复错误的导入. (2认同)

djc*_*djc 8

在 test_something.py 中,执行以下操作:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestMyUnit, 'test'))
    return suite
Run Code Online (Sandbox Code Playgroud)

在 testController.py 中,执行以下操作:

from TestUnits import test_something

def suite():
    suite = unittest.TestSuite()
    suite.addTest(test_something.suite())
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')
Run Code Online (Sandbox Code Playgroud)