I want to do automated unit testing for my class that I had written in Python.
To do automated unit testing I need three items:
1. The class I want to test.
2. The unit testing class.
3. The test runner.
Step 1:
-------
I created my class and named it as controllerTesting.py.
I added functions inside the file as below:
class Test():
def returnZero(self):
return 0
def returnNonZero(self):
return 12
def returnSumNumber(self, number1, number2):
return number1 + number2
Step 2:
-------
I created the file (test.py) and add the functions to test the functions in controllerTesting.py
I added code as below:
import unittest
from controllers.controllerTesting import Test
class TestControllerTest(unittest.TestCase):
def testZeroReturn(self):
val = 0
t = Test()
self.assertEqual(val, t.returnZero())
def testNonZeroReturn(self):
val = 0
t = Test()
self.assertNotEqual(val, t.returnNonZero())
def testSumNumber(self):
total = 4
t = Test()
r = t.returnSumNumber(2, 2)
self.assertEqual(total, r, 'incorrect default size')
Step 3:
-------
I created the test runner (test_runner.py) and add these code to the file.
import unittest
from test import TestControllerTest
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestControllerTest)
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestControllerTest))
log_file = 'unit_testing_log.txt'
f = open(log_file, "w")
runner = unittest.TextTestRunner(f, verbosity=2).run(suite)
unittest.TextTestRunner(verbosity=2).run(suite)
Step 4:
-------
I Ran the unit test using the command.
python test_runner.py
The output of the testing were printed in unit_testing_log.txt located in the same directory of the unit testing file.
Output example:
testNonZeroReturn (test.TestControllerTest) ... ok
testSumNumber (test.TestControllerTest) ... FAIL
testZeroReturn (test.TestControllerTest) ... ok
testNonZeroReturn (test1.TestControllerTest2) ... ok
testSumNumber (test1.TestControllerTest2) ... ok
testZeroReturn (test1.TestControllerTest2) ... ok
======================================================================
FAIL: testSumNumber (test.TestControllerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 33, in testSumNumber
self.assertEqual(total, r, 'incorrect default size')
AssertionError: 4 != 0 : incorrect default size
----------------------------------------------------------------------
Ran 6 tests in 0.001s
FAILED (failures=1)