【问题标题】:how to write a unit testing function for my function?如何为我的功能编写单元测试功能?
【发布时间】:2017-10-12 15:51:23
【问题描述】:

这是我创建的函数:

def hab(h, a, b= None):
    if b != None:
        result = ("{} , {} , {}".format(h, b, a))
    else:
        result = ("{} , {}".format(h, a))
    return result

我正在尝试为我的函数编写单元测试,当提供两个或三个参数时,单元测试应该断言函数的正确性。

这是我的框架:

class hab_Test_Class(unittest.TestCase):
   def test_pass2(self):

   def test_pass3(self):

# i'll use code below to run the unit test
t = hab_Test_Class()
suite = unittest.TestLoader().loadTestsFromModule(t)
unittest.TextTestRunner().run(suite)

我真的不太了解单元测试在做什么,但不太明白。

【问题讨论】:

  • 请修正缩进。关注这个:stackoverflow.com/help/mcve
  • 您的问题不清楚。您知道您需要使用不同的参数测试函数是否正确,那么是什么阻止您编写测试并使用这些参数调用它并检查响应?

标签: python unit-testing


【解决方案1】:

假设你所有的代码都在main.py

def format_person_info(h, a, b= None):
    if b != None:
        a = ("{} , {} , {}".format(h, b, a))
    else:
        a = ("{} , {}".format(h, a))
    return a

您可以在tests.py 中为此方法运行单元测试,如下所示:

import main
import unittest
class hab_Test_Class(unittest.TestCase):
   def test_pass2(self):
       return_value = main.format_person_info("shovon","ar")
       self.assertIsInstance(return_value, str, "The return type is not string")
       self.assertEqual(return_value, "shovon , ar", "The return value does not match for 2 parameters")

   def test_pass3(self):
       return_value = main.format_person_info("shovon","ar",18)
       self.assertIsInstance(return_value, str, "The return type is not string")
       self.assertEqual(return_value, "shovon , 18 , ar",  "The return value does not match for 3 parameters")

# i will use code below to run the unit test
t = hab_Test_Class()
suite = unittest.TestLoader().loadTestsFromModule(t)
unittest.TextTestRunner().run(suite)

当您运行测试时,输出将如下所示:

..
----------------------------------------------------------------------
Ran 2 tests in 0.016s

OK

现在让我们看看我们做了什么。我们使用assertIsInstance 检查了返回类型是否为字符串,我们使用assertEqual 检查了两个和三个参数的输出。您可以使用assertEqual 的一组有效和无效测试来解决这个问题。官方文档在这个官方文档Unit testing framework中有关于unittest的简要说明。

【讨论】:

    【解决方案2】:

    通常,您会按照以下方式做某事:

    class NameAgeJob_Test_Class(unittest.TestCase):
        def test_pass_string_input_no_b(self):
            result = format_person_info('foo', 'bar')
            self.assertEqual(result, 'foo , bar')
    

    那里有很多documentation and examples

    【讨论】:

      猜你喜欢
      • 2014-07-05
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多