简体   繁体   English

Python 中“none”类型的单元测试

[英]Unit test for the 'none' type in Python

How would I 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 isn't any return value that I could compare it to.我不知道断言函数等于什么,因为没有任何返回值可以与它进行比较。

Would assertIn work? assertIn 会起作用吗?

All Python functions return something.所有 Python 函数都会返回一些东西。 If you don't specify a return value, None is returned.如果不指定返回值,则返回None So if your goal really is to make sure that something doesn't return a value, you can just say所以如果你的目标真的是确保某些东西不返回值,你可以说

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的函数。)

The point of a unit test is to test something that the function does.单元测试的重点是测试函数所做的事情。 If it's not returning a value, then what is it actually doing?如果它没有返回值,那么它实际上在做什么? In this case, it doesn't appear to be doing anything, since my_list is 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 char is actually appended to the list.然后你会想要测试char是否真的附加到列表中。 Your test would be:您的测试将是:

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 isn't any point testing for it (unless you need make sure that it doesn't return a value).由于该函数不返回值,因此对其进行测试没有任何意义(除非您需要确保它不返回值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM