验证调用另一个构造函数的构造函数

问题描述 投票:0回答:1

我想验证

Foo()
调用
Bar()
而无需实际调用
Bar()
。然后我想验证
obj
是否已分配给
Bar()
返回的任何内容。

我尝试了以下方法:

class Bar:
    def __init__(self, a):
        print(a)

class Foo:
    def __init__(self):
        self.obj = Bar(1)

###

import pytest
from unittest.mock import Mock, patch
from mod import Foo, Bar

@pytest.fixture # With stdlib
def mock_bar():
    with patch('mod.Bar') as mock:
        yield mock

def test_foo(mock_bar):
    result = Foo()
    mock_bar.assert_called_once_with(1)
    assert result.obj == mock_bar

但它会失败并说:

E       AssertionError: assert <MagicMock na...='5265642864'> == <MagicMock na...='5265421696'>
E         Full diff:
E         - <MagicMock name='Bar' id='5265421696'>
E         ?                                 ^ ^^
E         + <MagicMock name='Bar()' id='5265642864'>
E         ?                     ++          +  ^ ^
python pytest python-unittest.mock
1个回答
0
投票

这一行:

assert result.obj == mock_bar

应该是:

assert result.obj == mock_bar.return_value

Bar 中分配的是调用

self.obj = Bar(1)
结果
,而不是
Bar
本身。

© www.soinside.com 2019 - 2024. All rights reserved.