python中无类型的单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14868170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:42:47  来源:igfitidea点击:

unittest for none type in python?

pythonunit-testingassertionnonetype

提问by peppy

I was just wondering how I would go about testing for a function that does not return anything. for example, say I have this function:

我只是想知道如何测试一个不返回任何内容的函数。例如,假设我有这个功能:

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

and then if I were to test it:

然后如果我要测试它:

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)

I don't know what to assert the function is equal to, since there is no return value that I could compare it to.

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

EDIT: would assertIn work?

编辑: assertIn 会起作用吗?

回答by aquavitae

The point of a unit test is to test something that the function does. If its not returning a value, then what is it actually doing? In this case, it doesn't appear to be doing anything, since my_listis a local variable, but if your function actually looked something like this:

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

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

Then you would want to test if charis actually appended to the list. Your test would be:

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

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

Since the function does not return a value, there's no point testing for it (unless you need make sure that it doesn't return a value).

由于该函数不返回值,因此没有必要对其进行测试(除非您需要确保它不返回值)。

回答by Kevin Christopher Henry

All Python functions return something. If you don't specify a return value, Noneis returned. So if your goal really is to make sure that something doesn't return a value, you can just say

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

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

(However, this can't distinguish between a function without an explicit return value and one which does return None.)

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