如何为我的函数编写单元测试函数? [英] how to write a unit testing function for my function?

查看:30
本文介绍了如何为我的函数编写单元测试函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我创建的一个函数:

This is a function i created:

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

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

I'm trying to write a unit testing for my function, the unit test should assert the function correctness when two or three parameters are provided.

这是我的框架:

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)

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

I really have little sense of what the unit testing is doing, but not quite get it.

推荐答案

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

Suppose you have all your codes in 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 中为该方法运行单元测试,如下所示:

You can run unit test for this method like below in 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)

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

When you run the tests the output will be like below:

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

OK

现在让我们看看我们做了什么.我们使用 assertIsInstance 检查返回类型是否为我们预期的字符串,我们使用 assertEqual 检查了两个和三个参数的输出.您可以使用 assertEqual 使用一组有效和无效的测试来玩这个.官方文档在这个官方文档单元测试框架中有关于unittest的简要说明.

Now lets see what we have done. We checked that the return type is string as we expected using assertIsInstance and we checked the output for two and three parameters using assertEqual. You may play with this using a set of valid and invalid tests with assertEqual. The official documentation has a brief description about unittest in this official doc Unit testing framework.

这篇关于如何为我的函数编写单元测试函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆