python - 如何在Python中进行单元测试以检查输入不为空

标签 python python-unittest assertion

这是我第一次尝试用 Python 编写单元测试。我有一个像这样的简单函数:

def sum_num(a, b):
  return a+b

我想做单元测试来检查输入(a,b)不为空并且输出不为空。

import unittest

class SumTest(unittest.TestCase):
    def test_sum_output_not_null(self):
        self.assertTrue(add_num(3,4))

    def test_sum_input_not_null(self):
        # How to check input (a and b) is not None ?
        self.assertIsNotNone(a)
...

suite = unittest.TestLoader().loadTestsFromTestCase(SumTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)

我在单元测试运行中遇到错误..

test_sum_input_not_null (__main__.SumTest) ... ERROR
test_sum_output_not_null (__main__.SumTest) ... ok

======================================================================
ERROR: test_sum_input_not_null (__main__.SumTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<command-1933936>", line 7, in test_sum_input_not_null
    self.assertIsNotNone(a)
NameError: name 'a' is not defined

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)
Out[4]: <unittest.runner.TextTestResult run=2 errors=1 failures=0>

如何检查 a 和 b 不为空?可能还想检查 a 和 b 是否也是整数。我在某处读到过有关 setup() 的内容。我需要这样做来测试函数的输入吗?

最佳答案

I want to do unit test to check that the input (a, b) is not null and output is not null.

要么您还不明白测试的目的,要么您正在问一些与 TDD 相关的问题。

你不测试引用,你测试当这种情况发生时你的函数是否处理得很好。

因此,您应该创建测试函数并在其中进行调用,如下所示:

def test_when_a_is_null(self):
    self.assertIsNotNone(add_num(None, 5))

当 b 为 None 且两者均为 None 时,情况类似。

但是,这意味着您的函数应该处理以下条件:

def add_num(a, b):
    if a is not None and b is not None:
        return a + b
    elif a is not None:
        return a
    elif b is not None:
        return b
    return 0

关于python - 如何在Python中进行单元测试以检查输入不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56888330/

相关文章:

c - Linux 代码块上的断言 'value' 失败

ruby - Watir 检查文本是否存在

Cypress 等待保存窗口消失

python-3.x - 任何级别的日志记录都可以让 assertLogs 通过

python - Multiprocessing Manager().dict() 更新失败

python - 检查某个键是否存在于包含函数返回的多个字典的元组中的任何字典中

python - 如何在 python 中模拟 "+"运算符(特别是 datetime.date + datetime.timedelta)

Python 单元测试字典断言 KeyError

python - 发现后过滤测试

python - PyOpenGl 还是 pyglet?