How to pass variable to test class

P

Podi

Hi,

Newbie question about unittest. I am having trouble passing a variable
to a test class object.

MyCase class will potentially have many test functions.

Any help would be much appreciated.

Thanks,
P

# File MyCase.py
import unittest

class MyCase(unittest.TestCase):
def __init__(self, value):
super(MyCase, self).__init__()
self.value = value
def test1(self):
print self.value
def test2(self):
print 'world'

if __name__ == '__main__':
msg = 'Hello'
myCase = MyCase(msg)
suite = unittest.TestSuite()
suite.addTest(myCase)
unittest.TextTestRunner(verbosity=2).run(suite)


D:\MyWorks>MyCase.py
Traceback (most recent call last):
File "D:\MyWorks\MyCase.py", line 14, in ?
myCase = MyCase(msg)
File "D:\MyWorks\MyCase.py", line 5, in __init__
super(MyCase, self).__init__()
File "C:\Python24\lib\unittest.py", line 208, in __init__
raise ValueError, "no such test method in %s: %s" % \
ValueError: no such test method in <class '__main__.MyCase'>: runTest
 
P

Peter Otten

Podi said:
Newbie question about unittest. I am having trouble passing a variable
to a test class object.

MyCase class will potentially have many test functions.

By default a unittest.TestCase has only one test function called "runTest".
Therefore you have to add multiple instances of your TestCase subclass to
the suite and to pass the test function's name to the initializer
explicitly:

import unittest

class MyTestCase(unittest.TestCase):
def __init__(self, testname, value):
super(MyTestCase, self).__init__(testname)
self.value = value
def test1(self):
pass
def test2(self):
pass

if __name__ == "__main__":
value = 42

suite = unittest.TestSuite()
suite.addTest(MyTestCase("test1", value))
suite.addTest(MyTestCase("test2", value))

unittest.TextTestRunner(verbosity=2).run(suite)

However, the standard place for common setup is in the setUp() method.

Peter
 
P

Podi

Thanks for replying.

I need to pass some external values to the test cases because I want to
run the same tests in different environments such as lab/instrument
setup.

Regards,
Podi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top