【问题标题】:Unit test for the 'none' type in PythonPython中“无”类型的单元测试
【发布时间】:2013-01-29 20:41:15
【问题描述】:

我将如何测试一个不返回任何内容的函数?

比如说我有这个功能:

def is_in(char):
    my_list = []
    my_list.append(char)

如果我要测试它:

class TestIsIn(unittest.TestCase):

    def test_one(self):
    ''' Test if one character was added to the list'''
    self.assertEqual(self.is_in('a'), # And this is where I am lost)

我不知道要断言函数等于什么,因为没有任何返回值可以与之比较。

assertIn 会起作用吗?

【问题讨论】:

    标签: python unit-testing assertion nonetype


    【解决方案1】:

    单元测试的重点是测试函数所做的事情。如果它没有返回一个值,那么它实际上在做什么?在这种情况下,它似乎没有做任何事情,因为 my_list 是一个局部变量,但如果你的函数实际上看起来像这样:

    def is_in(char, my_list):
        my_list.append(char)
    

    然后你会想要测试char 是否真的附加到列表中。你的测试是:

    def test_one(self):
        my_list = []
        is_in('a', my_list)
        self.assertEqual(my_list, ['a'])
    

    由于函数不返回值,因此没有任何点测试它(除非您需要确保它不返回值)。

    【讨论】:

      【解决方案2】:

      所有 Python 函数都会返回一些东西。如果不指定返回值,则返回 None。因此,如果您的目标确实是确保某事不返回值,您可以说

      self.assertIsNone(self.is_in('a'))
      

      (但是,这无法区分没有显式返回值的函数和有return None 的函数。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-16
        • 2015-11-30
        相关资源
        最近更新 更多