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

17 投票
3 回答
9257 浏览
提问于 2025-04-17 18:39

我想把我的应用程序文件放在一个叫做 /Files 的文件夹里,而把测试单元放在 /UnitTests 文件夹里,这样可以清楚地区分应用和测试。

为了能够使用和 mainApp.py 一样的模块路径,我在根文件夹里创建了一个 testController.py 文件。

mainApp.py
testController.py
Files
  |__init__.py
  |Controllers
     | blabla.py
  | ...
UnitTests
  |__init__.py
  |test_something.py

所以如果在 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()


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

import TestUnits.test_something as my_test
my_test.unittest.main()

结果没有出现失败,但也没有执行任何测试。

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

OK
[Finished in 0.3s]


我尝试了一个没有依赖的测试,作为 "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()

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

3 个回答

-1

可以使用一个变通的方法,通过subprocess.call()来运行测试,比如:

import subprocess

args = ["python", "test_something.py"]
subprocess.call(args)
25

unittest.main() 这个方法会查看当前环境中所有的 unittest.TestCase 类。也就是说,你只需要在你的 testController.py 文件中导入你的测试类,然后在这个文件里调用 unittest.main() 就可以了。

所以,你的 testController.py 文件应该简单地像这样:

import unittest    
from UnitTests.test_something import *
unittest.main()
10

在test_something.py文件里,做这个:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestMyUnit, 'test'))
    return suite

在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')

撰写回答