如何在python中的另一个文件中调用类的方法[单元测试]

Ran*_*ith 5 python python-2.7 python-unittest

我想在另一个文件中调用类的方法,该类使用unittest.Testcase。您可以在下面找到示例片段,

class Introduction(unittest.TestCase):
  def test_case1(self):
    print "test 1"
  def test_case2(self):
    print "test 2"
if__name__=="main"
unittest.main()
Run Code Online (Sandbox Code Playgroud)

在这里我可以使用以下逻辑调用整个班级

introduction = unittest.TestLoader().loadTestsFromTestCase(Introduction)
unittest.TextTestRunner(verbosity=3).run(introduction)
Run Code Online (Sandbox Code Playgroud)

但我想在另一个文件中调用单个test_case2方法,请您帮帮我。

在此先感谢,Ranjith

ste*_*stt 3

你可以试试这个:

首先,您应该将包含Introduction.test_case2的python模块导入到您想要调用该test_case2的脚本中(让我们称之为“main_script”)

import unittest
from test_module_name import Introduction
Run Code Online (Sandbox Code Playgroud)

现在您可以执行此操作来调用“main_script”中的 test_case2

if __name__ == '__main__':
    unittest.main(defaultTest="Introduction.test_case2", exit=False)
Run Code Online (Sandbox Code Playgroud)