Unittest
Unit Testing in Python
Unit Testing is the first level of software testing where the smallest testable parts of a software are tested.
This is used to validate that each unit of the software performs as designed.
import unittest
class SimpleTest(unittest.TestCase): def test(self): self.assertTrue(True) if __name__ == '__main__': unittest.main()This is the basic test code using unittest framework, which is having a single test. This test() method will fail if TRUE is ever FALSE.
There are three types of possible test outcomes :
- OK – This means that all the tests are passed.
- FAIL – This means that the test did not pass and an AssertionError exception is raised.
- ERROR – This means that the test raises an exception other than AssertionError.
EXAMPLE :
import unittest class TestStringMethods(unittest.TestCase): def setUp(self): pass
def test_strings_a(self): self.assertEqual( 'a'*4, 'aaaa') def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_strip(self): s = 'geeksforgeeks' self.assertEqual(s.strip('geek'), 'sforgeeks') def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main()
Basic terms used in the code :
- assertEqual() – This statement is used to check if the result obtained is equal to the expected result.
- assertTrue() / assertFalse() – This statement is used to verify if a given statement is true or false.
- assertRaises() – This statement is used to raise a specific exception.
Comments
Post a Comment