robier / forge-object
Forge objects with ease
Installs: 8 308
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: ^7.2
Requires (Dev)
- infection/infection: ^0.12.2
- phpstan/phpstan: ^0.11.6
- phpunit/phpunit: ^8
Suggests
- fzaninotto/faker: Easy way to generate random valid data in your forge
This package is auto-updated.
Last update: 2024-10-17 11:46:24 UTC
README
Easily forge your own object for testing purposes (not intended for production code).
Heavily inspired by Larvel's factories but with one big difference, Laravel's factories are used for only creating or persisting models, but this library can create any type of object (model, entity, value object...). This library do not know how to persist something.
Library is framework agnostic and can be implemented in any framework.
Every test has a 3 main parts:
setup
- setting up application for testtest
- actual assertscleanup
- killing references in code or database
This library aims to reduce setup part of tests and also to reduce time needed for adding new data to object, especially when you use that object a lot in your tests.
If you find some feature that you would like to see in this library feel free to contribute or open an issue :).
Install
Library can be installed via composer:
composer require --dev robier/forge-object
Usage
First you need to register forge for your object:
$manager = new Robier\ForgeObject\Manager(); $manager->register(\stdClass::class, static function(): \stdClass{ // apply random valid data to object $object = new \stdClass(); $object->active = (bool)rand(0, 1); $object->admin = (bool)rand(0, 1); return $object; })
After registration you can add states to object:
$manager->registerState(\stdClass::class, 'active', static function(\stdClass $item): void{ // change random data with exact data in states $item->active = true; }) $manager->registerState(\stdClass::class, 'admin', static function(\stdClass $item): void{ // change random data with exact data in states $item->admin = true; })
Let's say you need one random stdClass object in your test:
$oneStdClassObject = $manager->new(\stdClass::class)->one();
Or you need a random stdClass that is active:
$oneStdClassObject = $manager->new(\stdClass::class)->state('active')->one();
Maybe you need multiple random stdClass objects that are active, let's say 15:
$manyActiveStdClassObjects = $manager->new(\stdClass::class)->state('active')->many(15);
States can be combined and they are applied in order they are provided to state
method. If you want random stdClass
that is also an active and admin you would do it like this:
$oneStdClassObject = $manager->new(\stdClass::class)->state('active', 'admin')->one();
Local development
Build docker with command
docker/build
Run any command inside docker
docker/run {script}
for example:
docker/run composer install
Run all tests:
docker/run composer run test