繁体   English   中英

如何测试一个对象是由另一个创建的?

[英]How to test that an object is created by another?

我有一个来自AA对象,它使用实例方法从B类创建另一个对象。 我想用pytest值为Trueattribute_to_check测试它是否正确创建

class B:
    def __init__(self, attribute_to_check=None):
        self.attribute_to_check = attribute_to_check or False
    
    def some_method():
        # some actions...

class A:
    def __init__(self, some_attr):
        self.some_attr = some_attr
        ...

    async def create_object_b(self, something_not_relevant):
       ...
       object_b = B(attribute_to_check=True)
       object_b.some_method()
       ...
       return None

编辑:上面的方法不返回object_b而是使用它的方法。

测试将是这样的:

async def test_object_created():
    object_A = A(some_attrs)
    await object_A.create_object_b(something_not_relevant="")
    # How can I access and assert object B is created with attribute_to_check == True?

我尝试为类B的对象创建一个固定装置,但这不会测试我的意图,即类A的函数使用属性的预期值实例化类B的对象。

我建议您重构方法create_object_b以仅创建 b 对象(与方法名称和方法行为一致)。 这样你就可以检查 B 是否是用你想要的属性创建的

class B:
    def __init__(self, attribute_to_check=None):
        self.attribute_to_check = attribute_to_check or False

    def some_method():
        # some actions...

class A:
    def __init__(self, some_attr):
        self.some_attr = some_attr
        ...

    async def create_object_b(self, something_not_relevant) -> B:
        ...
        object_b = B(attribute_to_check=True)
        ...
        return object_b

    async def make something_with_b(self, object_b: B):
        b.some_method()

测试班

async def test_object_created():
    object_A = A(some_attrs)
    object_b = await object_A.create_object_b(something_not_relevant="")

    assert object_b.some_attribute == True

暂无
暂无

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

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