DEV Community

Discussion on: How to write testable code

Collapse
hopeseekr profile image
Theodore R. Smith • Edited on

Instead of Mockery/Prophet, why do people not use anonymous classes? Oh, that's right. The vast majority of PHP developers have never bothered to learn them.

Take this:

   $account = Mockery::Mock(Account::class);
   $account->shouldReceive('setState')
       ->with('active')
       ->andReturn($account)
       ->once();
   $account->shouldReceive('save')
       ->andReturn($account)
       ->once();

It can be rewritten into this:

$account = new class extends Account {
    public function setState(string $state): self
    {
        return $this;
    }

    public function save(): self
    {
        return $this;
    }
};

These are largely the same. You can, if you need to, ensure that each of those functions are called only once (use static $runCount), then they would be largely identical.

Thread Thread
ddarrko profile image
Daniel Benzie Author

I use a mocking framework because it is consistent with what other developers I work alongside will use.

I would have no problems using an anonymous class but I don't see the benefit it offers over a mature, well tested and known library.