Skip to main content
 首页 » 编程设计

python之如何在 Python unittest.TestCase 中添加匹配器

2024年12月31日9虾米姐

datastructure = { 
     frame:"test" 
     position: 
          { 
           x: 1, 
           y: 2, 
          } 
     orientation: 
          { 
           w: 1.23, 
           z: 2.24, 
          } 
}  

我有自定义数据结构。我需要做一个 assertAlmostEqual(a, b)。但是上面的数据结构没有- (subtract) 运算符重载,因此assertAlmostEqual 不起作用

我可以像在 gmock matchers 中一样在 unittest.TestCase 中编写匹配器吗? . 例如,我想编写一个自定义版本的 assertAlmostEqualCustom

请您参考如下方法:

Can I write matchers in unittest.TestCase like in gmock matchers?

当然可以,许多项目已经在使用继承自 unittest.TestCase 的自己的 YourTestCase,例如class TestDataStrut(YourTestCase) 将被用来代替 class TestDataStruct(unittest.TestCase)。

如果你必须在一个大型项目中经常使用特定的断言,你必须自己做。

Django TestCase

Django testcases.py code

An Example of creating your own TestCase