【问题标题】:how to write Unittets for a method which is returning a method如何为返回方法的方法编写 Unittets
【发布时间】:2019-05-15 11:32:49
【问题描述】:
def acquisition_required(method):
    def wrapped_method(self, *args, **kwargs):
        result=some complex code
        if not result:
            some code is here
        else:
            return method(self, *args, **kwargs)
return wrapped_method

我想为此编写一个单元测试 例如。

assertEqual, assertTrue.. 但我不知道如何测试它我已经对返回一些值或真/假的函数进行了单元测试。 我不想要任何代码只是概念

【问题讨论】:

  • 你用同样的方法来做:你调用装饰器返回的方法,并验证它是否产生了预期的值。
  • @tobias_k 我做了一些更正,现在可以了

标签: python unit-testing


【解决方案1】:

如果你的函数成功了,那么返回值就是getting方法的引用。这意味着您可以使用 unittest 模块的 assertEqual 方法。如下:

import unittest 
import your_module

class ConfigParserTestCases(unittest.TestCase):

def test_return_method(self):
    self.assertEqual(your_module.acquisition_required(method), method)

if __name__ == "__main__":
    unittest.main()

注意:如果您的实现包含异常(例如:try-except 用于错误处理),您可以使用 unittest 模块的“assertRaises”方法测试异常情况。来自Official Python documentation

例如。在你的情况下(如果你想测试 ValueError 异常):

with self.assertRaises(ValueError):
    self.assertRaises(your_module.acquisition_required(method))

【讨论】:

  • 比较两个方法是否相等只是检查它们是否是同一个对象;不是很有用。
  • 我同意,但正如我所见,这个函数是一个装饰器,在正确工作的情况下,它的返回值与输入对象是同一个对象。正如我在回答中提到的那样,异常或错误处理等......是不同的故事。
  • 我遇到了如何在单元测试文件中导入方法(参数)等问题
【解决方案2】:

我做到了如下:

 with self.assertRaises(ValueError):
        self.assertRaises(your_module.acquisition_required(method))

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 2021-04-25
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    相关资源
    最近更新 更多