Skip to content

Commit dbd0d93

Browse files
authored
Merge pull request #11 from fetzi/feature/add-json-decoder-tests
Tests for JsonDecoder
2 parents 07de078 + f2835c1 commit dbd0d93

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

tests/specs/JsonDecoderSpec.php

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
<?php
2+
3+
namespace tests\specs\Karriere\JsonDecoder;
4+
5+
use Karriere\JsonDecoder\Bindings\CallbackBinding;
6+
use Karriere\JsonDecoder\ClassBindings;
7+
use Karriere\JsonDecoder\JsonDecoder;
8+
use Karriere\JsonDecoder\Transformer;
9+
use PhpSpec\ObjectBehavior;
10+
11+
class JsonDecoderSpec extends ObjectBehavior
12+
{
13+
public function let()
14+
{
15+
$this->beConstructedWith(false, false);
16+
}
17+
18+
public function it_is_initializable()
19+
{
20+
$this->shouldHaveType(JsonDecoder::class);
21+
}
22+
23+
public function it_should_allow_decoding_of_private_properties()
24+
{
25+
$this->beConstructedWith(true, false);
26+
$this->decodesPrivateProperties()->shouldReturn(true);
27+
}
28+
29+
public function it_should_allow_decoding_of_protected_properties()
30+
{
31+
$this->beConstructedWith(false, true);
32+
$this->decodesProtectedProperties()->shouldReturn(true);
33+
}
34+
35+
public function it_should_transform_raw_data()
36+
{
37+
$jsonString = '{"id": 1, "name": "John Doe"}';
38+
39+
$response = $this->decode($jsonString, JsonDecoderSample::class);
40+
41+
$response->shouldHaveType(JsonDecoderSample::class);
42+
$response->id->shouldBe(1);
43+
$response->name->shouldBe('John Doe');
44+
}
45+
46+
public function it_should_transform_by_using_custom_transformer()
47+
{
48+
$this->register(new SampleTransformer());
49+
50+
$jsonString = '{"id": 1, "firstname": "John", "lastname": "Doe"}';
51+
52+
$response = $this->decode($jsonString, JsonDecoderSample::class);
53+
54+
$response->shouldHaveType(JsonDecoderSample::class);
55+
$response->id->shouldBe(1);
56+
$response->name->shouldBe('John Doe');
57+
}
58+
59+
public function it_should_transform_empty_raw_data_to_null()
60+
{
61+
$jsonString = 'null';
62+
63+
$this->decode($jsonString, JsonDecoderSample::class)->shouldReturn(null);
64+
}
65+
}
66+
67+
class JsonDecoderSample
68+
{
69+
public $id;
70+
public $name;
71+
}
72+
73+
class SampleTransformer implements Transformer
74+
{
75+
public function register(ClassBindings $classBindings)
76+
{
77+
$classBindings->register(new CallbackBinding('name', function ($data) {
78+
return sprintf('%s %s', $data['firstname'], $data['lastname']);
79+
}));
80+
}
81+
82+
public function transforms()
83+
{
84+
return JsonDecoderSample::class;
85+
}
86+
}

0 commit comments

Comments
 (0)