How to test django model method __str__()

一世执手 提交于 2021-02-06 16:06:04

问题


I trying to test __str__ method, and when trying to access it in my test it returns my model instance (I think it is)

def test_str_is_equal_to_title(self):
    """
    Method `__str__` should be equal to field `title`
    """
    work = Work.objects.get(pk=1)
    self.assertEqual(work.__str__, work.title)

And from test I get:

AssertionError: '<bound method Work.__str__ of <Work: Test title>>' != 'Test title'

How I should compare these 2 values to pass test?


回答1:


According to the documentation:

Model.__str__()

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

You need to call str() on the model instance:

self.assertEqual(str(work), work.title)



回答2:


Alternatively, you may simply call it like:

model_instance.__str__()



来源:https://stackoverflow.com/questions/29077509/how-to-test-django-model-method-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!