CollectionTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Yansongda\Supports\Tests;
  3. use PHPUnit\Framework\TestCase;
  4. use Yansongda\Supports\Collection;
  5. class CollectionTest extends TestCase
  6. {
  7. /**
  8. * data.
  9. *
  10. * @var array
  11. */
  12. protected $data = [];
  13. /**
  14. * collection.
  15. *
  16. * @var Collection
  17. */
  18. protected $collection;
  19. protected function setUp(): void
  20. {
  21. $this->data = [
  22. 'name' => 'yansongda',
  23. 'age' => 26,
  24. 'sex' => 1,
  25. 'language' => [
  26. 'php',
  27. 'java',
  28. 'rust',
  29. ],
  30. ];
  31. $this->collection = new Collection($this->data);
  32. }
  33. public function testToString()
  34. {
  35. $json = json_encode($this->data);
  36. self::assertEquals($json, $this->collection->toJson());
  37. self::assertEquals($json, $this->collection->__toString());
  38. }
  39. public function testMagicGet()
  40. {
  41. self::assertEquals('yansongda', $this->collection->name);
  42. self::assertEqualsCanonicalizing(['php', 'java', 'rust'], $this->collection->language);
  43. }
  44. public function testMagicSet()
  45. {
  46. $this->collection->fuck = 'ok';
  47. $this->collection->foo = ['bar', 'fuck'];
  48. self::assertEquals('ok', $this->collection->get('fuck'));
  49. self::assertEquals(['bar', 'fuck'], $this->collection->get('foo'));
  50. }
  51. public function testIsset()
  52. {
  53. self::assertTrue(isset($this->collection['name']));
  54. self::assertFalse(isset($this->collection['notExistKey']));
  55. }
  56. public function testUnset()
  57. {
  58. unset($this->collection['name']);
  59. self::assertFalse(isset($this->collection['name']));
  60. }
  61. public function testAll()
  62. {
  63. self::assertEquals($this->data, $this->collection->all());
  64. }
  65. public function testOnly()
  66. {
  67. self::assertEquals([
  68. 'name' => 'yansongda',
  69. ], $this->collection->only(['name']));
  70. }
  71. public function testExcept()
  72. {
  73. self::assertEquals([
  74. 'name' => 'yansongda',
  75. 'age' => 26,
  76. 'sex' => 1,
  77. ], $this->collection->except('language')->all());
  78. }
  79. public function testMerge()
  80. {
  81. $merge = ['haha' => 'enen'];
  82. self::assertEqualsCanonicalizing(array_merge($this->data, $merge), $this->collection->merge($merge)->all());
  83. }
  84. }