使用Python進行自動化軟體測試


在本教程中,我們將學習如何在Python中進行自動化測試。編寫程式碼後,我們需要透過提供不同型別的輸入來測試它們,並檢查程式碼是否正常工作。

我們可以手動或自動執行此操作。手動測試非常困難。因此,我們將學習如何在Python中進行自動化測試。讓我們開始吧。

我們有一個名為**unittest**的模組,用於自動測試程式碼。在本教程中,我們將使用此模組。對於初學者來說,使用**unittest**模組進行測試非常簡單。讓我們從基礎開始編碼。

您要測試的方法必須以**test**文字開頭。

示例

# importing unittest module
import unittest
class SampleTest(unittest.TestCase):
   # return True or False
   def test(self):
      self.assertTrue(True)
# running the test
unittest.main()

輸出

如果執行以上程式,您將得到以下結果。

Ran 1 test in 0.001s
OK

測試字串方法

現在,我們將使用示例測試用例測試不同的字串方法。請記住,方法名稱必須以**test**開頭。

示例

# importing unittest module
import unittest
class TestingStringMethods(unittest.TestCase):
   # string equal
   def test_string_equality(self):
      # if both arguments are then it's succes
      self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')
   # comparing the two strings
   def test_string_case(self):
      # if both arguments are then it's succes
      self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')
   # checking whether a string is upper or not
   def test_is_string_upper(self):
      # used to check whether the statement is True or False
      self.assertTrue('TUTORIALSPOINT'.isupper())
      self.assertFalse('TUTORIALSpoint'.isupper())
# running the tests
unittest.main()

輸出

如果執行以上程式,您將得到以下結果。

Ran 3 tests in 0.001s
OK

結論

您可以在程式中使用測試來節省大量時間。如果您對本教程有任何疑問,請在評論區提出。

更新於:2019年11月1日

612 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.