📜  Python unittest – assertNotEqual()函数

📅  最后修改于: 2022-05-13 01:54:20.882000             🧑  作者: Mango

Python unittest – assertNotEqual()函数

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

句法:

参数: assertNotEqual() 接受下面列出的三个参数,并附有说明:

  • firstValue:函数比较中使用的任何类型的变量
  • secondValue:函数比较中使用的任何类型的变量
  • message:一个字符串语句,作为测试用例失败时显示的消息。

下面列出了两个不同的示例,说明了给定断言函数的正负测试用例:

示例 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 = "geeksg"
        # error message in case if test case got failed
        message = "First value and second value are not unequal !"
        # assertNotEqual() to check unequality of first & second value
        self.assertNotEqual(firstValue, secondValue, message)
  
if __name__ == '__main__':
    unittest.main()


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 unequal !"
        # assertNotEqual() to check equality of first & second value
        self.assertNotEqual(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.assertNotEqual(firstValue, secondValue, message)
AssertionError: 'geeks' == 'geeks' : First value and second value are not unequal!

----------------------------------------------------------------------
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 unequal !"
        # assertNotEqual() to check equality of first & second value
        self.assertNotEqual(firstValue, secondValue, message)
  
if __name__ == '__main__':
    unittest.main()

输出:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

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