1.

Explain the concept of unit testing with a simple example.

Answer»

Unit testing is one of the various software testing methods where individual units/ components of software are tested. Unit testing refers to tests that verify the functionality of a specific section of code, usually at the function level. 

The UNITTEST module is a part of Python’s standard library. This unit testing framework was originally inspired by JUNIT. Individual units of source code, such as functions, methods, and class are tested to determine whether they are fit for use. Intuitively, one can view a unit as the smallest testable part of an application. Unit tests are short code FRAGMENTS created by programmers during the development process.

TEST case is the smallest unit of testing. This checks for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.

test suite is a collection of test cases, test suites, or both and is used to aggregate tests that should be executed together. Test suites are implemented by the TestSuite class.

Following code is a simple example of unit test using TestCase class.

First let us define a function to be tested. In the following example, add() function is to be tested.

Next step is to Create a testcase by subclassing unittest.TestCase.

Inside the class, define a test as a method with name starting with 'test'.

Each test call assert function of TestCase class. The assertEquals() function compares result of add() function with arg2 ARGUMENT and throws assertionError if comparison fails.

import unittest def add(x,y):    return x + y class SimpleTest(unittest.TestCase):    def testadd1(self):       self.assertEquals(add(10,20),30) if __name__ == '__main__':    unittest.main()

Run above script. Output shows that the test is passed.

Ran 1 test in 0.060s OK

Possible outcomes are:

  • OK: test passes
  • FAIL: test doesn’t pass and AssertionError exception is raised.
  • ERROR: test raises exception other than AssertionError

The unittest module also has a command line interface to be run using Python’s -m option.

Python -m unittest example.py


Discussion

No Comment Found