项目作者: MayMeow

项目描述 :
:robot: Plugin to generate testing data with Factories using Faker
高级语言: PHP
项目地址: git://github.com/MayMeow/cakephp-testing.git
创建时间: 2019-10-06T08:04:55Z
项目社区:https://github.com/MayMeow/cakephp-testing

开源协议:

下载


MayMeow/Testing plugin for CakePHP

Plugin for easier writing tests for CakePHP. Create factories to create testing data with Faker instead of
loading TableRegistry and calling new entity and save

Installation

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

  1. composer require maymeow/cakephp-testing

And load it to your project

How to use it

First what you need to do is write factory for your model. Skeleton looks like

  1. <?php
  2. namespace Identity\Database\Factories;
  3. use Faker\Generator;
  4. use MayMeow\Testing\Factories\ModelFactory;
  5. use MayMeow\Testing\Factories\ModelFactoryInterface;
  6. class UserFactory implements ModelFactoryInterface
  7. {
  8. /**
  9. * @param array|null $data
  10. * @return \Cake\Datasource\EntityInterface|false
  11. */
  12. public function get(array $data = null)
  13. {
  14. $factory = new ModelFactory($data);
  15. return $factory->define('Identity.Users', function (Generator $faker) {
  16. return [
  17. // Your model data
  18. ];
  19. });
  20. }
  21. }

Then you can add your data. For now factories only support belongs to relationship.

  1. // ...
  2. eturn $factory->define('Identity.Users', function (Generator $faker) use ($api_key_plain) {
  3. return [
  4. 'email' => $faker->email,
  5. 'password' => (new \Cake\Auth\DefaultPasswordHasher())->hash('pa$$word'),
  6. // Belogs to delation can be added by calling another factory
  7. 'role_id' => function () {
  8. return (new RoleFactory())->get()->id;
  9. },
  10. 'api_key_plain' => $api_key_plain,
  11. 'api_key' => (new \Cake\Auth\DefaultPasswordHasher())->hash($api_key_plain)
  12. ];
  13. });
  14. // ...

After you have created your factories you can call them in your test for example in setuUp function.

  1. $this->user = (new UserFactory())->get();

When you need add relation or just want update any field in factory you can do this as following

  1. $this->post = (new PostFactory())->get(['address_id' => $address->id]);

Relationships

Plugin only support creating BelongsTo relations. So if you need to create relations User -> HasMany -> Posts you
have to create user and then many posts with user_id of this user

  1. // EXAMPLE Create 10 posts for one user
  2. $this->user = (new UserFactory())->get();
  3. for ($i=1; $i<=10; $i++) {
  4. (new PostFactory())->get(['user_id' => $this->user->id]);
  5. }

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

License

MIT

Support

You can support me on my patreon