assertequal用法python_Python unittest assertEqual()用法及代码示例

本文介绍了Python单元测试库中的assertEqual()函数,用于验证两个值是否相等。当值相等时,函数返回true,否则返回false。提供了负面和正面测试用例的示例,展示了在值不等和相等时的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中的assertEqual()是单元测试库函数,用于单元测试中以检查两个值的相等性。此函数将使用三个参数作为输入,并根据断言条件返回布尔值。如果两个输入值相等,则assertEqual()将返回true,否则返回false。

用法: assertEqual(firstValue, secondValue, message)

参数:assertEqual()接受以下说明的三个参数:

firstValue按功能比较中使用的任何类型的变量

secondValue:按功能比较时使用的任何类型的变量

message:作为测试消息失败时显示的消息的字符串语句。

下面列出了两个不同的示例,它们说明了给定assert函数的正面和负面测试案例:

示例1:否定测试用例

Python3

# unit test case

import unittest

class TestStringMethods(unittest.TestCase):

# test function to test equality of two value

def test_negative(self):

firstValue = "geeks"

secondValue = "gfg"

# error message in case if test case got failed

message = "First value and second value are not equal !"

# assertEqual() to check equality of first & second value

self.assertEqual(firstValue, secondValue, message)

if __name__ == '__main__':

unittest.main()

输出:

F

======================================================================

FAIL:test_negative (__main__.TestStringMethods)

----------------------------------------------------------------------

Traceback (most recent call last):

File "p1.py", line 12, in test_negative

self.assertEqual(firstValue, secondValue, message)

AssertionError:'geeks' != 'gfg'

- geeks

+ gfg

:First value and second value are not equal!

----------------------------------------------------------------------

Ran 1 test in 0.000s

FAILED (failures=1)

示例2:正测试用例

Python3

# unit test case

import unittest

class TestStringMethods(unittest.TestCase):

# test function to test equality of two value

def test_positive(self):

firstValue = "geeks"

secondValue = "geeks"

# error message in case if test case got failed

message = "First value and second value are not equal !"

# assertEqual() to check equality of first & second value

self.assertEqual(firstValue, secondValue, message)

if __name__ == '__main__':

unittest.main()

输出:

.

----------------------------------------------------------------------

Ran 1 test in 0.000s

OK

参考:https://docs.python.org/3/library/unittest.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值