phpunit 只模拟类的一个方法

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

我正在编写一个集成测试,只想模拟类中的单个方法,以防止它与“外部世界”接触

我的类有 2 个公共方法,我想用回调替换方法“dispatchMessage”,它只是返回我的输入值而不做任何进一步的事情。

我目前的尝试是这样的:

        /* @var ChargeReportServiceInterface $mock */
        $reportService = $this
            ->getMockBuilder(ChargeReportServiceInterface::class)
            ->enableOriginalConstructor()
            ->onlyMethods(['dispatchMessage'])
            ->getMock();
        $reportService
            ->method('dispatchMessage')
            ->willReturnCallback(
                function ($message) {
                    return $message;
                }
            );

        return $reportService;

这会导致消息:

PHP Fatal error:  Class MockObject_ChargeReportServiceInterface_fde2b860 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

仅模拟“dispatchMessage”方法并保留其余部分的正确方法是什么?

phpunit php-8 symfony6
1个回答
0
投票

以下代码有效:

        /* @var ChargeReportService $mock */
        $reportService = $this
            ->getMockBuilder(ChargeReportService::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['dispatchMessage'])
            ->getMock();
        $reportService
            ->method('dispatchMessage')
            ->willReturnCallback(
                function ($message) {
                    return $message;
                }
            );

        return $reportService;

所以我用类本身替换了接口。然后我禁用了构造函数,因为幸运的是我不需要任何注入的对象。 等等瞧!我可以访问 $message 的返回值,而该类的其他公共方法按预期工作。

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