Test jednostkowy Pythona – funkcja AssertEqual().
AssertEqual() w Pythonie to funkcja biblioteczna testu jednostkowego używana w testach jednostkowych w celu sprawdzenia równości dwóch wartości. Ta funkcja przyjmuje trzy parametry jako dane wejściowe i zwraca wartość logiczną w zależności od warunku potwierdzenia. Jeśli obie wartości wejściowe są równe, funkcjaasserEqual() zwróci wartość true, w przeciwnym razie zwróci wartość false.
Składnia: AssertEqual(pierwszawartość, drugawartość, wiadomość)
Parametry: asserEqual() akceptuje trzy parametry wymienione poniżej wraz z wyjaśnieniem:
FirstValue zmienna dowolnego typu, która jest używana w porównaniu przez funkcję SecondValue : zmienna dowolnego typu, która jest używana w porównaniu przez funkcję message : zdanie tekstowe jako komunikat, który został wyświetlony, gdy przypadek testowy zakończył się niepowodzeniem.
Poniżej znajdują się dwa różne przykłady ilustrujące pozytywny i negatywny przypadek testowy dla danej funkcji asertywności:
Przykład 1: Negatywny przypadek testowy
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()> |
Wyjście:
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)
Przykład 2: Pozytywny przypadek testowy
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()> |
Wyjście:
. ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
Odniesienie : https://docs.python.org/3/library/unittest.html