【问题标题】:How to call a method of class in another file in python [unit test]如何在python中调用另一个文件中的类方法[单元测试]
【发布时间】:2017-05-02 20:28:05
【问题描述】:

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

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

在这里我可以使用下面的逻辑调用整个类

introduction = unittest.TestLoader().loadTestsFromTestCase(Introduction)
unittest.TextTestRunner(verbosity=3).run(introduction)

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

提前致谢, 兰吉特

【问题讨论】:

标签: python python-2.7 python-unittest


【解决方案1】:

你可以试试这个:

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

import unittest
from test_module_name import Introduction

现在你可以在你的“main_script”中调用test_case2

if __name__ == '__main__':
    unittest.main(defaultTest="Introduction.test_case2", exit=False)

【讨论】:

  • 另外,如果你想运行多个测试,你可以将它们添加到一个列表中,它看起来像这样:defaultTest=["test_1", "test2", ... , "test_N"]
【解决方案2】:

我得到了从一个类中调用单个方法的逻辑,请找到下面的逻辑来解决

import Introduction
suite = unittest.TestSuite()
suite.addTest(Introduction('test_case1'))
print suite
unittest.TextTestRunner().run(suite)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2020-08-24
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多