0

Here's an example:

from unittest import TestCase


class DogTest(TestCase):

    def create_dog(self, weight):

        dog = {'weight': weight}

        return dog


class DogPawTest(TestCase):

    def test_dog_paw(self):

        dog_test = DogTest()
        dog = dog_test.create_dog(weight=10)
        self.assertEqual(dog['weight'], 10)

It throws

ValueError: no such test method in <class 'unittest_case_import.DogTest'>: runTest

Test cases should be independent. Also, create_dog can and should be outside of the test class. Changing the definition to DogTest(object) solves the riddle. But I have a case where it's not an option.

How can I use the methods of another TestCase-based class in test_dog_paw?

2
  • you can use DogPawTest(DogTest) in DogPawTest. and use self.create_dog(weight=10 Commented Dec 18, 2017 at 9:21
  • @ManojJadhav Alas, in my case I have to import multiple TestCase classes within a single class. Mixins may help, but it'd involve much refactoring. Commented Dec 18, 2017 at 9:29

1 Answer 1

1

With the example you have provided I don't see any need for inheritance. You could just as easily do something like:

from unittest import TestCase

def create_dog(weight):
    return {'weight': weight}

class DogTest(TestCase):
    def test_dogs(self):
        heavy_dog = create_dog(25)
        ...

class DogPawTest(TestCase):
    def test_dog_paw(self):
        dog = create_dog(weight=10)
        self.assertEqual(dog['weight'], 10)

It could also be worth having a look at something like PyTest's fixtures. That might change this code to be something like:

from unittest import TestCase
import pytest

@pytest.fixture
def dog():
    """Just your regular average dog"""
    return {'weight': 15}

@pytest.fixture
def heavy_dog():
    return {'weight': 30}

@pytest.fixture
def light_dog():
    return {'weight': 10}

class DogTest(TestCase):
    def test_dogs(self, heavy_dog):
        ...

class DogPawTest(TestCase):
    def test_dog_paw(self, dog):
        self.assertEqual(dog['weight'], 10)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I have the code that forces me to inherit, so I was looking for short ways to create an instance of an established test case.
Well, my answer is not really applicable then I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.