问题
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 callstr()
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