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 thatremoveuses. - You want to mock the
whereanddeletecalls so thatdeletethrows an exception, simulating a database error. - Also, you want to assert that the
Log::errormethod is called as expected.
Here's how you can do it:
use Illuminate\Support\Facades\Log;
use Mockery;
use Tests\TestCase;
class MedusaConfigTest extends TestCase
{
public function testRemoveDatabaseErrorLogsMessageAndReturnsFalse()
{
// Arrange: Mock the query builder that Eloquent returns from where()
$queryMock = Mockery::mock();
$queryMock->shouldReceive('delete')
->once()
->andThrow(new \Exception('Database error'));
// Mock the static where() method on MedusaConfig to return our query mock
$modelMock = Mockery::mock('alias:App\\Models\\MedusaConfig');
$modelMock->shouldReceive('where')
->with('key', '=', 'some.key')
->once()
->andReturn($queryMock);
// Mock the Log facade
Log::shouldReceive('error')
->once()
->withArgs(function ($message) {
return str_starts_with($message, 'Database error');
});
// Act
$value = \App\Models\MedusaConfig::remove('some.key');
// Assert
$this->assertFalse($value, 'Value should be false on error');
}
}
Explanation
- Mocking
where: We mock the staticwheremethod to return a mock object whosedeletemethod will throw an exception. - Not mocking
remove: This ensures the real logic inremoveruns, including the try/catch. - Mocking
Log::error: We assert that logging happens as expected. - Assertion: We check that the return value is
falsewhen 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.