I have gone through docs but did not understand unittesting in real sense in python.
i have a test code can anyone will tell me how to do unittestng on it?
a = 1
b = 2
def test():
c = a + 2
if c > 5:
z = 7
else:
z = 8
answer = b + z
return answer
Tim Pietzcker
338k59 gold badges521 silver badges572 bronze badges
2 Answers 2
To test your test() method you should create a test file like this
import unittest
from your_file import test
class TestMethodTestCase(unittest.TestCase):
def test_01a(self):
""" test the test method"""
self.failUnlessEqual(9, test(a=4, b=2)) # here you write all the use case you need to be sure that your method is correctly doing the job
self.failUnlessEqual(10, test(a=1, b=2))
self.failUnlessEqual(11, test(a=5, b=3))
if __name__=="__main__":
unittest.main()
with your test() method defined like this :
def test(a=1, b=2):
c = a + 2
if c > 5:
z = 7
else:
z = 8
answer = b + z
return answer
Have a look to python unittest documentation
answered May 15, 2011 at 8:31
Cédric Julien
81.2k16 gold badges131 silver badges134 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
pinky
hey wats this 10, 9, 8 u passed? we only pass functional parameter then waht r those?
Cédric Julien
the first parameter of failUnlessEqual() is the expected result of the tested method.
pinky
oh ok. and if i wanted expected result to be not less than zero and not more than 10 then?
Cédric Julien
You can use the assertGreater methods if you are in python > 2.7 : docs.python.org/library/…
Unit testing doesn't mean much more than just automated checking of the output of various functions in your code when they are given certain values. Basically, you just want to make sure that those tests don't break when you're changing things.
answered May 14, 2011 at 22:11
supercheetah
3,2504 gold badges29 silver badges39 bronze badges
2 Comments
pinky
means if i use name__=='__main':, will it called as unit testing?
Noufal Ibrahim
No. The
__main__ trick is used to prevent modules from executing if you import them.lang-py
test(a, b)). In that case you'd try it with several different arguments and check that it returns the expected value in all cases.