Search code examples
pythondjangounit-testingpycharmcoverage.py

Python test coverage for class' __str__


I have a very basic questing regarding Python coverage tests using PyCharm IDE. In my Django models, all the __str__ methods are not covered in my tests.

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

What would be the appropriate way to test these?

This doesn't work, the test runs but the __str__ method is still not seen as covered.

class TestCategory(TestCase):

    def test_category(self):
        category = Category.objects.create(name='Test Category')
        self.assertEqual(category.__str__(), 'Test Category')

Solution

  • The __str__() method is called whenever you call str() on an object.

    You should try it using str() method on the instance object.

    class TestCategory(TestCase):
    
        def test_category(self):
            category = Category.objects.create(name='Test Category')
            self.assertEqual(str(category), 'Test Category')