JSON requests and responses
Arrays and scalar data
Use matchJsonBody()
when passing PHP data. JSON object key order and insignificant whitespace do not affect matching.
$pock->matchMethod(RequestMethod::POST)
->matchUri('https://api.example.com/users')
->matchJsonBody(['name' => 'Jane', 'active' => true])
->reply(201)
->withHeader('Content-Type', 'application/json')
->withJson(['id' => 42]);
Use matchSerializedJsonBody()
when the expectation is already JSON text, or when an array already represents decoded JSON:
$pock->matchSerializedJsonBody('{"name":"Jane","roles":["admin"]}');
Invalid JSON throws Pock\Exception\JsonException
while the mock is configured or matched.
Objects and DTOs
Objects implementing JsonSerializable
use their jsonSerialize()
representation. Other objects require JMS Serializer or Symfony Serializer:
composer require --dev jms/serializer
$pock->matchJsonBody(new CreateUser('Jane'))
->reply(201)
->withJson(new User(42, 'Jane'));
pock discovers serializers in this order: JMS Serializer, then Symfony Serializer. Arrays fall back to native JSON encoding if a discovered serializer cannot handle them.
Selecting a serializer
Set an adapter before building mocks when project-specific serializer configuration is required:
use Pock\Factory\JsonSerializerFactory;
use Pock\Serializer\SymfonySerializerAdapter;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
JsonSerializerFactory::setSerializer(new SymfonySerializerAdapter($serializer, 'json'));
For another serialization library, implement Pock\Serializer\SerializerInterface
or use CallbackSerializerAdapter
:
use Pock\Serializer\CallbackSerializerAdapter;
JsonSerializerFactory::setSerializer(new CallbackSerializerAdapter(
static function ($value) {
return json_encode($value);
}
));