Tuesday, 17 May 2016

Unit Testing -Debugging the code

Testing is very much important to ensure the quality of product in any field. In Software development it is essential to point out the defects and errors in any program. Its a good practice to test your code . So I started with Unit Testing after I have learned Python programming language. In unit testing we use a module called unittest using which we can test our code. It is a testing framework . It comes pre-installed with python from 2.1.

The standard workflow is:
 1. Firstly we define our own class derived from unittest.TestCase.
 2. Then we fill it with functions that start with ‘test_’.
 3. After that we run the tests by placing unittest.main() in your file,        usually at the bottom.


 Before writing unit testcase, we should have few things in our mind that our
 testcase should be able to:
  • Run completely by itself, without any human input. Unit testing is about automation.
  • Determine by itself whether the function it is testing has passed or failed, without a human interpreting the results.
  • Run in isolation, separate from any other test cases (even if they test the same functions).

In unit test we also have setUp() and tearDown() function which are optional.  The setUp() function is used to set up the test environment and tearDown()  is used to clean up after a test. Setup method will run prior to each test case and teardown method will run after each test case.
We use assert functions to check whether the result is correct or not. There are a lot of assert functions in unittest.
Some of them are listed below:
assertEqual()
assertTrue()
assertFalse()
assertNotEqual()
assertIs()

To run a unittest, at the bottom of the test file,we have to give this code:

 if __name__ = "__main__":
     unittest.main()

This allows us to run all of the test code just by running the file.
Running it with no options is the most terse, and running with a ‘-v’ is more
verbose, showing which tests ran.   

No comments:

Post a Comment