diff --git a/src/PockBuilder.php b/src/PockBuilder.php index 2751e0d..52d56dd 100644 --- a/src/PockBuilder.php +++ b/src/PockBuilder.php @@ -317,6 +317,23 @@ class PockBuilder )); } + /** + * Match JSON request body against JSON string or array with data. + * + * @param array|string $data + * + * @return self + * @throws \Pock\Exception\JsonException + */ + public function matchSerializedJsonBody($data): self + { + if (is_string($data)) { + $data = self::jsonDecode($data, true); + } + + return $this->addMatcher(new JsonBodyMatcher($data)); + } + /** * Match XML request body using raw XML data. * @@ -324,11 +341,12 @@ class PockBuilder * It also doesn't serializer values with available XML serializer. * Use PockBuilder::matchSerializedXmlBody if you want to execute available serializer. * - * @see \Pock\PockBuilder::matchSerializedXmlBody() - * * @param DOMDocument|\Psr\Http\Message\StreamInterface|resource|string $data * * @return self + * @throws \Pock\Exception\XmlException + * @see \Pock\PockBuilder::matchSerializedXmlBody() + * */ public function matchXmlBody($data): self { diff --git a/tests/src/PockBuilderTest.php b/tests/src/PockBuilderTest.php index 507367e..3c97f1a 100644 --- a/tests/src/PockBuilderTest.php +++ b/tests/src/PockBuilderTest.php @@ -711,6 +711,19 @@ EOF; ->withHeader('Content-Type', 'text/plain') ->withBody('Second token (post json)'); + $builder->matchMethod(RequestMethod::POST) + ->matchScheme(RequestScheme::HTTPS) + ->matchHost(self::TEST_HOST) + ->matchPath('/ping') + ->matchHeaders([ + 'Authorization' => 'Token token_3', + 'Content-Type' => 'application/json' + ]) + ->matchSerializedJsonBody('{"field": "value3"}') + ->reply(200) + ->withHeader('Content-Type', 'text/plain') + ->withBody('Third token (post json with match against serialized data)'); + $builder->matchMethod(RequestMethod::POST) ->matchScheme(RequestScheme::HTTPS) ->matchHost(self::TEST_HOST) @@ -779,6 +792,19 @@ EOF; ); self::assertEquals('Second token (post json)', $response->getBody()->getContents()); + $response = $client->sendRequest( + self::getPsr17Factory() + ->createRequest(RequestMethod::POST, self::TEST_URI) + ->withHeader('Authorization', 'Token token_3') + ->withHeader('Content-Type', 'application/json') + ->withUri(self::getPsr17Factory()->createUri(self::TEST_URI . 'ping')) + ->withBody(self::getPsr17Factory()->createStream('{"field": "value3"}')) + ); + self::assertEquals( + 'Third token (post json with match against serialized data)', + $response->getBody()->getContents() + ); + $response = $client->sendRequest( self::getPsr17Factory() ->createRequest(RequestMethod::POST, self::TEST_URI)