5

I want to call a method of class in another file, the class is using unittest.Testcase. You can find example snippet below,

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

Here i can able to call the entire class by using below logic

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

but i want call a single test_case2 method in another file, can you please help me out.

Thanks in advance, Ranjith

Ranjith
  • 103
  • 1
  • 7
  • Possible duplicate of http://stackoverflow.com/questions/14282783/call-a-python-unittest-from-another-script-and-export-all-the-error-messages – Satyadev May 02 '17 at 11:13
  • The above ticket has calling entire class but i want a single method inside the class. the test runner snippet is also mentioned in description – Ranjith May 02 '17 at 11:41

2 Answers2

3

You can try this one:

Firstly you should import the python module that holds Introduction.test_case2 into the script you from which you want to call that test_case2 (lets call it "main_script")

import unittest
from test_module_name import Introduction

Now you can do this to call the test_case2 in your "main_script"

if __name__ == '__main__':
    unittest.main(defaultTest="Introduction.test_case2", exit=False)
stefan.stt
  • 2,357
  • 5
  • 24
  • 47
  • Also if you want to run multiple tests, you can add them to a list and it would look something like that: **defaultTest=["test_1", "test2", ... , "test_N"]** – stefan.stt May 03 '17 at 05:44
2

I got the logic to call a single method from a class, please find the below logic to resolve

import Introduction
suite = unittest.TestSuite()
suite.addTest(Introduction('test_case1'))
print suite
unittest.TextTestRunner().run(suite)
Ranjith
  • 103
  • 1
  • 7