I am currently writing tests using Django’s unit tests (based on Python standard library module: unittest). I have written this test for my Contact model which passes:
class ContactTestCase(TestCase):
def setUp(self):
"""Create model objects."""
Contact.objects.create(
name='Jane Doe',
email='[email protected]',
phone='+2348123940567',
subject='Sample Subject',
message='This is my test message for Contact object.'
)
def test_user_can_compose_message(self):
""" Test whether a user can compose a messsage in the contact form."""
test_user = Contact.objects.get(name='Jane Doe')
self.assertEqual(test_user.email, '[email protected]')
self.assertEqual(test_user.phone, '+2348123940567')
self.assertEqual(test_user.subject, 'Sample Subject')
self.assertEqual(test_user.message, 'This is my test message for Contact object.')
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.005s
OK
Destroying test database for alias 'default'...
However, I had to use the assertEqual
method 4 times in this test (could be more when testing models with more fields). It seems like this doesn’t follow the DRY principle.
I know from the docs that assertEqual(first, second, msg=None)
tests that first and second are equal. If the values do not compare equal, the test will fail.
Is there a workaround or a more elegant approach to writing such tests?