DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

Certain conventions must be followed for a unit test.
While you can create a unit test that has the code that
you want to test all in the same file, it’s a better idea to
use object-oriented principles when building tests. In
this case, the function you want to test is saved as
areacircle.py, so following good practices you should
name your unit test file test_areacircle.py. This makes it
easy to differentiate the two. You should also import the
unittest module, and from areacircle you can import the
area_of_circle function. Import the pi method from
math so that you can test your results. The import
statements would look as follows:


Click here to view code image


import unittest
from areacircle import area_of_circle
from math import pi

Next, you need to create a class for your test. You can
name it whatever you want, but you need to inherit
unittest.TestCase from the unittest module. This is
what enables the test function methods to be assigned to
your test class. Next, you can define your first test
function. In this case, you can test various inputs to
validate that the math in your function under test is
working as it should. You will notice a new method called
assertAlmostEqual(), which takes the function you
are testing, passes a value to it, and checks the returned
value against an expected value. You can add a number
of tests to this function. This is what the test now looks
like with the additional code:


Click here to view code image


class
Test_Area_of_Circle_input(unittest.TestCase):
def test_area(self):
# Test radius >= 0
Free download pdf