Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cinnion's avatar

Issues testing a static model method which calls delete()

Hello,

I am trying to test a static method in a model class to see that it handles exceptions properly. The method reads as follows:

    public static function remove(string $key): bool
    {
        try {
            self::where('key', '=', $key)->delete();

            return true;
        } catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());

            return false;
        }
    }

The current implementation of the unit test reads as follows:

Sadly, the test is failing on the assertFalse and I am getting a dump of what appears to be a mock of my model class, showing that the exception does not appear to be thrown. Any ideas on how to get this test working for both the return value and logging?

I am using L11 with PHPUnit 11.

0 likes
2 replies
LaryAI's avatar
Level 58

Certainly! The issue here is that you are mocking the remove method itself, which means your test never actually runs the real logic inside MedusaConfig::remove(). Instead, it just returns a mock object, so the exception is never thrown and caught.

Key Points:

  • Don't mock the method under test (remove). Instead, mock the underlying Eloquent query chain that remove uses.
  • You want to mock the where and delete calls so that delete throws an exception, simulating a database error.
  • Also, you want to assert that the Log::error method is called as expected.

Here's how you can do it:



Explanation

  • Mocking where: We mock the static where method to return a mock object whose delete method will throw an exception.
  • Not mocking remove: This ensures the real logic in remove runs, including the try/catch.
  • Mocking Log::error: We assert that logging happens as expected.
  • Assertion: We check that the return value is false when an exception is thrown.

Notes

  • Adjust the namespace (App\\Models\\MedusaConfig) as needed for your app.
  • If you use Laravel's built-in testing helpers, you may need to add use Illuminate\Support\Facades\Log; and ensure the Facade is set up for testing.

This approach allows you to test both the exception handling and the logging behavior of your static method.

cinnion's avatar

The above code gives me an error that the remove method does not exist on the mock object. And when I try to replace the setup of the where mocking with

        $modelMock = $this->partialMock(MedusaConfig::class, function ($mock) use ($queryMock) {
            $mock->shouldReceive('where')
                ->with('key', '=', 'some.key')
                ->once()
                ->andReturn($queryMock);
        });

it does not appear to throw the exception.

Please or to participate in this conversation.