简体   繁体   English

单元测试初始化​​期间调用的方法?

[英]Unit testing a method called during initialization?

I have a class like the following: 我有一个像下面这样的课程:

class Positive(object):
    def __init__(self, item):
        self._validate_item(item)
        self.item = item

    def _validate_item(self, item):
        if item <= 0:
            raise ValueError("item should be positive.")

I'd like to write a unit test for _validate_item() , like the following: 我想为_validate_item()编写单元测试,如下所示:

class PositiveTests(unittest.TestCase):
    def test_validate_item_error(self):
        self.assertRaises(
            ValueError,
            Positive._validate_item,
            0
        )

Unfortunately, this won't work because the unit test only passes 0 to the method, instead of a class instance (for the self parameter) and the 0. Is there any solution to this other than having to test this validation method indirectly via the __init__() of the class? 不幸的是,这是行不通的,因为单元测试仅将0传递给该方法,而不是将类实例(用于self参数)和0传递给该方法。除了必须通过间接测试该验证方法之外,还有其他解决方案吗?该类的__init__()

If you're not using self in the method's body, it's a hint that it might not need to be a class member. 如果您不在方法的主体中使用self,则暗示它可能不必是类成员。 You can either move the _validate_item function into module scope: 您可以将_validate_item函数移入模块范围:

def _validate_item(item):
    if item <= 0:
        raise ValueError("item should be positive.")

Or if it really has to stay in the class, the mark the method static: 或者,如果确实必须将其留在类中,则将方法标记为静态:

class Positive(object):
    def __init__(self, item):
        self._validate_item(item)
        self.item = item

    @staticmethod
    def _validate_item(item):
        if item <= 0:
            raise ValueError("item should be positive.")

Your test should then work as written. 然后,您的测试应按书面要求进行。

You're not creating an instance of Positive. 您没有创建Positive实例。 How about 怎么样

Positive()._validate_item, 0

Well, _validate_item() is tested through the constructor. 好吧,_validate_item()是通过构造函数测试的。 Invoking it with a null or negative value will raise the ValueError exception. 用null或负值调用它会引发ValueError异常。

Taking a step back, that's the goal no ? 退后一步,这是目标吗? The "requirement" is that object shall not be created with a zero or negative value. “要求”是不得创建具有零或负值的对象。

Now this is a contrived example, so the above could not be applicable to the real class ; 现在这是一个人为的示例,因此以上内容不适用于实际类; another possibility, to really have a test dedicated to the _validate_item() method, could be to create an object with a positive value, and then to invoke the validate_item() on it. 真正进行_validate_item()方法专用测试的另一种可能性是,创建一个具有正值的对象,然后在其上调用validate_item()。

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

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