saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.03k stars 105 forks source link

feat(testing): allow merging data in mocked fixture responses #425

Open innocenzi opened 3 months ago

innocenzi commented 3 months ago

Closes https://github.com/saloonphp/saloon/issues/416

This pull request allows merging data in fixtures:

MockResponse::fixture('user', merge: [
    'name' => 'Sam Carré',
])

This is useful when the mocked response is used by other part of the code that depends on it, and assertions are performed later on the result of that code.

One (very) simple example of that would be testing if a data transfer object can be created:

$response = connector()->send(new DTORequest, new MockClient([
    MockResponse::fixture('user', merge: [
        'name' => 'Sam Carré',
    ]),
]));

expect($response->dto())
    ->name->toBe('Sam Carré') // Sam Carré instead of Sam
    ->actualName->toBe('Sam')
    ->twitter->toBe('@carre_sam');
innocenzi commented 3 months ago

One small concern I have is that this code uses array_merge, while I'm certain to have use cases where array_merge_recursive would be more useful.

I wanted to stay consistent with implementations of MergeableBody which all use array_merge. Would you be open to a PR that updates all of these to array_merge_recursive?

innocenzi commented 2 months ago

@Sammyjo20 do you think you could take a look at that? this would really ease testing requests 🙏

innocenzi commented 2 months ago

You can amend my previous concern, I refactored the pull request to support dot-notation, which fixes the issue.

I've been testing this in a work project, array_merge was not enough most of the time, and I needed dot-notation support for most fixtures.

Sammyjo20 commented 2 months ago

Hey @innocenzi thank you for this PR, it looks like a great addition! The only thing I ask is instead of having it as a second argument could we have a method that chains onto the ::fixture() call? Like MockResponse::fixture()->merge([]) because I've got an upcoming feature that will also share this API so it would be good if it was unified. What do you think?

innocenzi commented 2 months ago

That's a nice idea—I updated the PR!