unittest assertequals的用法
时间: 2023-08-16 20:07:48 浏览: 39
unittest中的`assertEqual()`方法用于比较两个值是否相等。它接受两个参数,分别是实际值和期望值。如果实际值与期望值相等,则断言通过;否则,断言失败。
以下是`assertEqual()`方法的用法示例:
```python
import unittest
class MyTestCase(unittest.TestCase):
def test_equal_values(self):
self.assertEqual(2 + 2, 4) # 断言通过,因为2 + 2 = 4
def test_unequal_values(self):
self.assertEqual(3 * 5, 12) # 断言失败,因为3 * 5 != 12
if __name__ == '__main__':
unittest.main()
```
在上面的示例中,我们定义了一个继承自`unittest.TestCase`的测试类`MyTestCase`。该类中有两个测试方法`test_equal_values()`和`test_unequal_values()`。
在`test_equal_values()`方法中,我们使用`self.assertEqual(2 + 2, 4)`进行断言。由于2 + 2等于4,所以断言通过。
而在`test_unequal_values()`方法中,我们使用`self.assertEqual(3 * 5, 12)`进行断言。由于3 * 5不等于12,所以断言失败。
运行这个测试类时,可以看到测试结果中显示了断言失败的信息。这样可以方便地验证代码的正确性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)