Django管理命令:my_custom_command.py

from django.core.management.base import BaseCommand

from services.external import ExternalApi


class Command(BaseCommand):
    def handle(self, *args, **options):
        api = ExternalApi()
        api.my_custom_method("param")


测试代码:

from django.core.management import call_command

from myapp.management.commands import my_custom_command


def test_custom_command(mocker):
    mocker.patch.object(my_custom_command, 'ExternalApi')
    call_command('my_custom_command')
    my_custom_command.ExternalApi.my_custom_method.assert_called_with('param')


结果:

    def test_custom_command(mocker):
        mocker.patch.object(my_custom_command, 'ExternalApi')
        call_command('my_custom_command')
>       my_custom_command.ExternalApi.my_custom_method.assert_called_with('param')
E       AssertionError: Expected call: my_custom_method('param')
E       Not called


尽管已调用my_custom_method,但测试找不到方法调用。似乎缺少上下文。能否请你帮忙?

最佳答案

您要声明类本身,而不是类实例。例:

api_cls_mock = mocker.patch.object(my_custom_command, 'ExternalApi')
# this line will get the method mock of ExternalApi's instances:
meth_mock = api_mock.return_value.my_custom_method
call_command('my_custom_command')
# method mock will track the calls
meth_mock.assert_called_with('param')

07-24 09:45