Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest Python - Why Create a Class?

Tags:

python

testing

Suppose you are writing unit tests with the unittest framework within Python.

I am used to writing unit tests using classes and various methods for each test e.g. if you had some function cuboid_volume that calculates the volume of a cube:

def cuboid_volume(l):
    return (l*l*l)

Then you would structure units tests as follows:

import unittest

class TestCuboid(unittest.TestCase):
    def test_volume(self):
      self.assertAlmostEqual(cuboid_volume(2),8)
    

However I have also seen examples where unit tests are structured without using a class. Example below:

def test_volume():
  assert cuboid_volume(2) == 8

My question is: what is the benefit of doing this and why use a class in the first place?

like image 750
Mike Tauber Avatar asked Apr 13 '26 22:04

Mike Tauber


1 Answers

benefit to use class

  1. you can call inheritted method from class unittest.TestCase, that is why you can use self.assertAlmostEqual
  2. group relevant test cases in a class so that they can share common data/properties among relevant test cases. also have same setUp and tearDown called per test method, or setUpClass and tearDownClass per class.
like image 112
gftea Avatar answered Apr 15 '26 10:04

gftea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!