我目前正在使用 Django 的单元测试(基于 Python 标准库模块:unittest)编写测试。我已经为我的联系人模型编写了这个测试,该测试通过了:
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'...
但是,在这个测试中我不得不使用
assertEqual
方法 4 次(当测试具有更多字段的模型时可能会更多)。看来这不符合 DRY 原则。
我从 docs 知道
assertEqual(first, second, msg=None)
测试第一个和第二个是否相等。如果值比较不相等,测试将失败。
是否有解决方法或更优雅的方法来编写此类测试?
完美的问题!欢迎来到质量测试社区!
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')
test_cases = {'email': '[email protected]', 'phone': '+2348123940567', 'subject': 'Sample Subject', 'message': 'This is my test message for Contact object.'}
for field, value in test_cases.items():
with self.subTest("wrong user subtest", field=field, ):
self.assertEqual(getattr(test_user, field), value)