I'm working with Laravel 10 and starting to study testing and mocking.
I've built a basic entity that has some simple properties and two images, that, for simplicity, I'm storing locally and saving the path relative to storage in the database.
I've create the following factory for the model:
<?php
// ...
class SpaceFactory extends Factory
{
public function definition(): array
{
return [
'name' => $this->faker->company,
'description' => $this->faker->sentence,
'profile_path' => str_replace('storage/app/', '', $this->faker->image('storage/app/spaces')),
'banner_path' => str_replace('storage/app/', '', $this->faker->image('storage/app/spaces')),
'created_by' => User::factory()->create()->id,
];
}
}
The main problem I have is while testing, the tests seems very slow and I'm pretty sure it's because I'm creating 40 fake images every time in the index method test
<?php
// ...
class SpaceTest extends TestCase
{
use InteractsWithDatabase, RefreshDatabase;
public function setUp(): void
{
parent::setUp();
Storage::fake('local');
}
public function testUserCanListSpaces()
{
$mock = $this->partialMock(\Faker\Generator::class, function (\Mockery\MockInterface $mock) {
$mock->shouldReceive('image')->times(40)->andReturn('mocked_path.png');
});
$spaces = Space::factory()->count(20)->create();
$response = $this->getJson('/api/spaces');
$response->assertOk();
$response->assertJsonStructure([
'results',
'meta',
'links'
]);
}
}
I was able to mock the image method of \Faker\Generator::class and make it return a string while testing. The problem is that all the other formatters (I believe this is the name they use in faker?) are not implementend although I'm using a partial mock.
Test result while mocking faker generator:
https://prnt.sc/1KcTy0HjuWx9
What can I do to partially mock faker correctly? Or perhaps should I change my factory to use another fake image generation method?]