Cory
Cory

Reputation: 15615

How do you create a common method within a class that inherited from unittest.TestCase?

Let's say I have the following code:

file1.py

class TestA(unittest.TestCase)
   def test_something(self):
     results = something()
     self.common_verify_method(results)

   def common_verify_method(self, results)
       expected = expected_method()
       self.assertEqual(results, expected)  # this uses self.assertEqual

file2.py

Class TestB(unittest.TestCase):
    def my_other_code(self):
        results = do_something()
        # Here I would like to call common_verify_method() from file1.py

In file2.py, I would like to call call common_verify_method() from file1.py. One way I can call do this by inhereting from TestA in TestB. The following works OK:

Class TestMyOtherCode(TestA)
    def my_other_code(self):
        results = do_something()
        self.common_verify_method(results)

If I don't want to inherent from TestA, how can I call common_verify_method(). If I use composition, I get the following error:

Class TestMyOtherCode(unittest.TestCase)
    def my_other_code(self):
        results = do_something()
        test_a = TestA()
        test_a.common_verify_method(results)

ValueError: no such test method in <class 'tests.file1.TestA'>: runTest

Upvotes: 1

Views: 159

Answers (2)

Jay Venkat
Jay Venkat

Reputation: 397

I tried your code to get the expected result in both classes (i.e) TestA & TestMyOtherCode. I created two python files let's say Sample1 & Sample2.

Here is a code

Sample1.py

import unittest

class TestA(unittest.TestCase):
   def test_something(self):
     results = 5
     self.common_verify_method(results)

   def common_verify_method(self, results):
       expected = 5
       self.assertEqual(results, expected)

Sample2.py

from Sample1 import TestA
import unittest

class TestMyOtherCode(unittest.TestCase):

    def __init__(self):
        self.other = TestA

    def my_other_code(self):
        results = 5
        self.other.common_verify_method(results)

I used Composition method in python. It works fine and gave expected result.

Try it...

Upvotes: 1

quamrana
quamrana

Reputation: 39354

Instead of TestB inheriting from TestA, or the other way round, they should both inherit from a common base class:

class CommonBase(unittest.TestCase)
   def common_verify_method(self, results)
       expected = expected_method()
       self.assertEqual(results, expected)  # this uses self.assertEqual

class TestA(CommonBase):
...

Upvotes: 3

Related Questions