phpunit only mock one method of a class

23 views Asked by At

I am writing an integration test and just want to mock a single method in my class to prevent it to make contact with the "outside world"

My class has 2 public methods and I want to replace the method 'dispatchMessage' with a callback, which just gives me back my input value without doing anything further.

My current attempt is this:

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

        return $reportService;

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

What is the correct way to only mock the 'dispatchMessage' method and leave the rest as is?

1

There are 1 answers

0
Calamity Jane On BEST ANSWER

What works is the following code:

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

        return $reportService;

So I replaced the interface with the class itself. Then I disabled the constructor because luckily I didn't need any of the injected objects. And et voilá! I can access my returned value of $message, while the other public method of the class works as intended.