I am a complete novice in testing and I wanted to know if someone could guide me on what I'm doing wrong. I want to test the following function in my php laravel project:
public static function getFlatSupplierAddress($supplier_address_id): string
{
$supplierAddress = Address::findOrFail($supplier_address_id);
return $supplierAddress->street . " " .
$supplierAddress->number . " " .
$supplierAddress->apartment . ", " .
($supplierAddress->city ? $supplierAddress->city->name : '') . ", " .
($supplierAddress->province ? $supplierAddress->province->name : '') . ", " .
($supplierAddress->country ? $supplierAddress->country->name : '');
}
This is my test code:
it('returns the formatted supplier address', function () {
$addressMock = Mockery::mock(Address::class);
$addressMock->shouldReceive('findOrFail')
->with(1)
->andReturnSelf(); // Retorna el mismo mock
$addressMock->shouldReceive('getAttribute')
->with('street')
->andReturn('Calle');
$addressMock->shouldReceive('getAttribute')
->with('number')
->andReturn('456');
$addressMock->shouldReceive('getAttribute')
->with('apartment')
->andReturn('Apt 789');
$addressMock->shouldReceive('city')
->andReturn((object)['name' => 'Retiro']);
$addressMock->shouldReceive('province')
->andReturn((object)['name' => 'Buenos Aires']);
$addressMock->shouldReceive('country')
->andReturn((object)['name' => 'Argentina']);
$expectedAddress = 'Calle 456 , Retiro, Buenos Aires, Argentina';
$formattedAddress = AddressService::getFlatSupplierAddress(1);
// Assert
expect($formattedAddress)->toBe($expectedAddress);
Of course I have the problem that I am not using well the Mock since the function returns me a string of an address that it found in the database and it is comparing it with the Mock that I have created. I don't understand how to simulate this kind of things. And of course I used ChatGPT D:
source https://stackoverflow.com/questions/77018462/testing-with-pest
No comments:
Post a Comment