使用Python进行自动化软件测试

在本教程中,我们将学习有关在Python中自动化测试的知识。编写代码后,我们必须通过提供不同类型的输入来测试它们,并检查代码是否正常工作。

我们可以手动或自动执行。进行手动测试非常困难。因此,我们将学习Python中的自动化测试。开始吧。

我们有一个名为unittest的模块,该模块用于自动测试代码。在本教程中,我们将使用此模块。对于初学者来说,直接使用unittest模块进行测试非常简单。让我们从基础开始编码。

您必须测试的方法必须以测试文本开头。

示例

# 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('nhooo'.upper(), 'nhooo')
   # 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('nhooo'.isupper())
      self.assertFalse('nhooo'.isupper())
# running the tests
unittest.main()

输出结果

如果运行上面的程序,您将得到以下结果。

Ran 3 tests in 0.001s
OK

结论

您可以在程序中使用测试以节省大量时间。如果您对本教程有任何疑问,请在评论部分中提及。