【问题标题】:Python mockito - how to verify method's fieldsPython mockito - 如何验证方法的字段
【发布时间】:2022-07-15 06:51:37
【问题描述】:

我在单元测试中使用 python mockito。对mockito的能力比较熟悉,比如verify、mock、capture等,但是不知道怎么验证方法的fileds的值。

我的生产代码。

class Dog(BaseModel):
    type: str
    age: int

    def bark(self, times: int) -> None:
        print(f"{self.type} {self.age}  {'ruf' * times}")


class FlowManager:

    def __init__(self, barks: int, dog_type: str, age: int):
        self.barks = barks
        self.dog_type = dog_type
        self.age = age

    def foo(self):
        # Some code....
        dog = Dog(type=self.dog_type, age=self.age)
        dog.bark(self.barks)
        # More some code...

这是涵盖“FlowManager”类的“foo”方法的单元测试。

from mockito import verify, when
class TestFlowManager(unittest.TestCase):

    def test_foo_happy_flow(self):
        # Arrange
        when(Dog).bark(...).thenReturn(None)

        # Act
        num_of_barks = 5
        dog_type = "bulldog"
        dog_age = 3
        FlowManager(num_of_barks, dog_type, dog_age).foo()

        # Assert
        verify(Dog).bark(num_of_barks)

我的问题是:我如何断言 Dog 对象的属性。换句话说:我如何断言使用 dog_type=="bulldog" 和 dog_age==3 创建的 Dog 类?

谢谢!

【问题讨论】:

  • 澄清:BaseModel类来自Pydantic(from pydantic import BaseModel)

标签: python unit-testing mockito


【解决方案1】:

您似乎没有将Dog 注入FlowManager 或其方法。在foo 中,您调用了一个全局模块Dog,因此您可能必须拦截它:

when(module_under_test).Dog(type="bulldog", age=3).thenReturn(mock())

由于when 配置非常具体,您可能不需要验证任何内容。 (foo 的类型为 None -> None;这只是一个意外的副作用 :grin :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多