使用有序字典(OrderedDict)代替普通字典。
示例代码:
import unittest from collections import OrderedDict
class MyTest(unittest.TestCase): def test_my_method(self): my_dict = {'a': 1, 'b': 2, 'c': 3} # 普通字典无法保证顺序一致 expected_output = {'b': 2, 'a': 1, 'c': 3} # 使用有序字典来保持顺序一致 expected_output_ordered = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) # 正确的断言方式 self.assertDictEqual(my_dict, expected_output_ordered)
使用有序字典可以保持字典的键值对顺序一致,从而避免由于字典顺序不同导致的单元测试失败。
下一篇:避免元素在可拖动时被拖动