#1473·mockery

在模拟预期未满足但仍有其他方法调用时,改进了错误消息

作者: jacretney创建于 2025年10月4日更新于 2025年10月8日

I've been using Mockery for a while, and I've had an idea for an improvement I'd like to see. I've forked the repo and have put some time in to make a bit of a proof of concept, but I wanted to create this issue to see if there is any interest/feedback on this from other users and the maintainers as it might be a bit of a bigger change :)

My biggest complaint when using Mockery comes from mocking methods which have more than a few parameters. When creating the mocks, or when working on code that has tests using said mocks, it can be quite tricky to figure out why a mock expectation was not met.

I would love it if Mockery's failed expectation error during test execution could provide more context as to why the mock assertion failed. I also do front end work and use Jest for testing, and I quite like how that handles this situation. Here is an example PHP Class I want to mock: class Sunflower { private int $potWidth; private string $potShape; public function repot(int $potWidth, string $potShape): self { $this->potWidth = $potWidth; $this->potShape = $potShape; return $this; } } And here is an example test: public function testCanRepotASunflower(): void { $sunflowerMock = Mockery::mock(Sunflower::class); $sunflowerMock ->shouldReceive("repot") ->with([ "potWidth" => 5, "potShape" => "square", // parameter exists, but the actual value is different, ]) ->once(); $sunflowerMock->repot(5, "circle"); } This test will fail due to the $potShape parameter of the repot method not matching an expectation - we were expecting "square" to be provided rather than "circle". This is the feedback that Mockery gives: Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_1_Nature_Sunflower::repot(5, 'circle'). Either the method was unexpected or its arguments matched no expected argument list for this method In this trivial example, it's easy to spot the issue. However, we don't actually know what was provided instead of the expected value, so now I'd need to go through my code and start adding logs / dumps to try and find the culprit. This issue gets worse when there are more method parameters as there's now more things I might need to investigate. What prompted me to raise this issue and work on it was a long day of fixing mock expectations in a lot of tests for a method which had 8 parameters I found myself thinking this would be so much easier and quicker if the errors presented like they do in Jest. For comparison, Jest is able to show more context as to why this failed. Here is an equivalent test in Jest: const Sunflower = require("./Sunflower"); jest.mock("./Sunflower"); test("can repot a sunflower", () => { const sunflower = new Sunflower(); sunflower.repot(5, "circle"); expect(sunflower.repot).toHaveBeenCalledWith(5, "square"); });

内容来源: mockery/mockery