python-3.x - 如何将模拟对象传递给 pytest fixture

标签 python-3.x mocking pytest fixtures

抱歉标题,我一定要更新...我有一个pytest测试功能:

def test_update_db():
    mock_connection = Mock(spec=Connection)
    db_updater = DbUpdater(mock_connection)

    db_updater.run("some parameter")

    mock_connection.gna.assert_called_with("some different parameter")

这有效,但很难看:db_updater 应该真的是一个固定装置。但是我必须将连接对象传递给它,所以我宁愿:
@pytest.fixture
def db_updater():
    mock_connection = Mock(spec=Connection)
    return DbUpdater(mock_connection)


def test_update_db(db_updater):
    db_updater.run("some parameter")
    mock_connection.gna.assert_called_with("some different parameter")

有一个问题的更好的测试函数:mock_connection 在那里不存在......我该如何解决这个问题?

最佳答案

您可以定义一个 fixture 以依赖另一个 fixture ,然后在您的测试中将它们都设为 args。这应该有效:

import pytest

@pytest.fixture
def conn():
    return Mock(spec=Connection)

@pytest.fixture
def db_updater(conn):
    return DbUpdater(conn)

def test_update_db(conn, db_updater):
    db_updater.run("some parameter")
    conn.gna.assert_called_with("some different parameter")

关于python-3.x - 如何将模拟对象传递给 pytest fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893490/

相关文章:

python - 使用 __pycache__ 时 pytest 会隐藏警告

python - 使用 pytest,为什么单个测试结果与运行所有测试不同?

python - python 3.5 和 3.6 中出现奇怪的 strptime 错误

python - 用 python 在 Raspbian 中模拟击键

javascript - 如何模拟 Jasmine 中其他服务方法中调用的 $http.post 方法?

python - 当测试在单独的文件夹中时使用 pytest

python - 无法将日期转换为所需格式

java - 如何使用 Mockito 或任何其他相关的 java 框架模拟父类(super class)方法

java - Mockito中是否有类似于Junit Setup Method的东西