Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #364 from saloonphp/feature/v3-add-count-to-assert…
…-methods

Feature | V3 Added a request option to assertSentCount
  • Loading branch information
Sammyjo20 committed Jan 21, 2024
2 parents 1a69816 + 3e7afda commit fba00c0
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/Http/Faking/MockClient.php
Expand Up @@ -260,7 +260,9 @@ public function assertNotSent(string|callable $request): void
}

/**
* Assert JSON data was sent
* Assert JSON response data was received
*
* @deprecated This method will be removed in v4
*
* @param array<string, mixed> $data
*/
Expand All @@ -282,8 +284,16 @@ public function assertNothingSent(): void
/**
* Assert a request count has been met.
*/
public function assertSentCount(int $count): void
public function assertSentCount(int $count, string $requestClass = null): void
{
if (is_string($requestClass)) {
$actualCount = $this->getRequestSentCount()[$requestClass] ?? 0;

PHPUnit::assertEquals($count, $actualCount);

return;
}

PHPUnit::assertCount($count, $this->getRecordedResponses());
}

Expand Down Expand Up @@ -458,4 +468,18 @@ private function mockResponseValue(MockResponse|Fixture|callable $mockable, Pend

return $mockable($pendingRequest);
}

/**
* Get an array of requests recorded with their count
*
* @return array<class-string, int>
*/
private function getRequestSentCount(): array
{
$requests = array_map(static function (Response $response) {
return $response->getRequest()::class;
}, $this->getRecordedResponses());

return array_count_values($requests);
}
}
19 changes: 19 additions & 0 deletions tests/Unit/MockClientAssertionsTest.php
Expand Up @@ -163,6 +163,25 @@
$mockClient->assertSentCount(3);
});

test('can assert count of requests', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam']),
MockResponse::make(['name' => 'Taylor']),
MockResponse::make(['name' => 'Marcel']),
MockResponse::make(['message' => 'Error'], 500),
]);

$connector = new TestConnector;

$connector->send(new UserRequest, $mockClient);
$connector->send(new UserRequest, $mockClient);
$connector->send(new UserRequest, $mockClient);
$connector->send(new ErrorRequest, $mockClient);

$mockClient->assertSentCount(3, UserRequest::class);
$mockClient->assertSentCount(1, ErrorRequest::class);
});

test('assertSent with a closure works with more than one request in the history', function () {
$mockClient = new MockClient([
MockResponse::make(['name' => 'Sam']),
Expand Down

0 comments on commit fba00c0

Please sign in to comment.