Skip to content

Instantly share code, notes, and snippets.

@makomweb
Created June 14, 2022 10:32
Show Gist options
  • Save makomweb/18001c21565879936c4f49fcc1718361 to your computer and use it in GitHub Desktop.
Save makomweb/18001c21565879936c4f49fcc1718361 to your computer and use it in GitHub Desktop.
Serialize properties
<?php
declare(strict_types=1);
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Serializer\SerializerInterface;
class PropertiesTest extends KernelTestCase
{
private SerializerInterface $serializer;
protected function setUp(): void
{
parent::setUp();
$this->serializer = self::getContainer()
->get(SerializerInterface::class);
}
/** @test */
public function getting_unknown_property_throws(): void {
$model = new MyModel();
try
{
$value = $model->test;
self::fail('Should have thrown!');
} catch (Exception $exception)
{
self::assertTrue(true);
}
}
/** @test */
public function getting_known_property_should_pass(): void {
$model = new MyModel();
$model->value = 'test';
$value = $model->value;
self::assertSame('test', $value);
}
/** @test */
public function serializing_should_succeed(): void {
$model = new MyModel();
$model->value = 'test';
$json = $this->serializer->serialize($model, 'json');
self::assertGreaterThan(0, strlen($json));
}
}
class MyModel
{
private array $values;
public function __construct(array $values = []) {
$this->values = $values;
}
public function __get(string $key)
{
return $this->values[$key];
}
public function __set(string $key, $value)
{
$this->values[$key] = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment