如何断言已使用预期数据调用了该方法?

时间:2021-04-30 02:52:32

标签: python unit-testing mocking pytest

我有以下代码:

class CreateProfile:
    def __init__(self, profile_repository):
        self.profile_repository = profile_repository

    def __call__(self, create_profile_request):
        if self.profile_repository.exists_by_user_id(create_profile_request.user_id):
            raise ProfileAlreadyExists(create_profile_request.user_id)
        profile = Profile(create_profile_request.user_id, None, None, None, None)
        self.profile_repository.create(profile)

经过以下测试:

@patch("profile.core.service.create_profile.Profile")
def test_should_create_empty_profile(
    Profile, profile_repository, create_profile_request, service
):
    profile = ProfileFactory(user_id=sentinel.profile_id)
    Profile.return_value = profile
    service(create_profile_request)
    profile_repository.create.assert_called_with(profile)
    assert sentinel.profile_id == profile.id
    assert None is profile.name
    assert None is profile.nick
    assert None is profile.bio
    assert None is profile.status

问题是,如果对代码进行以下更改,测试仍然是绿色的。

class CreateProfile:
    def __init__(self, profile_repository):
        self.profile_repository = profile_repository

    def __call__(self, create_profile_request):
        if self.profile_repository.exists_by_user_id(create_profile_request.user_id):
            raise ProfileAlreadyExists(create_profile_request.user_id)
        profile = Profile(create_profile_request.user_id, None, None, None, None)
        id = profile.id
        profile.id = None
        self.profile_repository.create(profile)
        profile = id

虽然这个更改有点愚蠢,因此不会发生,但我觉得我在测试用例中遗漏了一些东西,因为我无法确定我发送到存储库的数据现在是正确的已被调用。我曾经写过一段代码来存储参数的副本,并制作方法模拟 side_effect 来执行它,然后检查已存储的数据,但似乎有人已经完成了,因为我没有发现像这样做的任何事情我被以下问题困住了:

我应该测试这个吗?如果是,我该怎么做才能正确?

1 个答案:

答案 0 :(得分:2)

我建议您考虑模拟您尝试执行的调用并利用 assert_called_with 功能。

我强烈推荐这个 video 以熟悉补丁功能和整个模拟。