This package allows you to generate PHPUnit tests from annotations, which you can write in your methods documentation.
The preferred way to install this extension is through composer.
Either run
composer require hyperia/codecept-unittest-generator:"^1.0"
or add
"hyperia/codecept-unittest-generator": "^1.0"
to the require section of your composer.json.
enable UnitGenerator
extension in base /codeception.yml
config file:
extensions:
enabled:
- CodeceptionExtensionRunFailed
commands:
- CodeceptionCommandUnitGenerator
unitgenerator:
config:
# erase old target files with new one
overwrite: true
# if you want to generate tests for Interface too
interface: false
# automaticaly generate tests for getter / setter method
auto: true
# ignore errors that can be ignored
ignore: true
# regex (/.*config.php/ for example) that files must not match to have a tests generation
exclude: '/.*Trait.*/'
# regex (/.*.php/ for example) that files should match to have a tests generation
include: '/.*.php/'
dirs:
# source directory => target directory
- common/models: tests/unit/unitgen/common/models/
- console/models: tests/unit/unitgen/console/models/
./vendor/bin/codecept generate:unit
/**
* @PHPUnitGen<phpunit_assertion_method>(<expectation>:{<parameters...>})
*/
This annotation use some parameters:
phpunit_assertion_method: It is the PHPUnit assertion method you want ot use (like assertEquals, assertInstanceOf, assertTrue ...).
expectation: The method return expected value. Some PHPUnit methods does not need it (like assertTrue), so in those cases, it can be null.
parameters: The method parameters.
See this example, we want to auto generate some simple test for this method:
<?php
// The class to test content
/** @PHPUnitGenAssertEquals('expected string':{1, 2, 'a string'}) */
/** @PHPUnitGenAssertTrue(:{4, 5, 'another'}) */
/** @PHPUnitGenAssertEquals(null) */
/** @PHPUnitGenAssertNull() */
public function method(int $arg1 = 0, int $arg2 = 0, string $arg3 = 'default') {}
Those annotations will create basic PHPUnit tests:
<?php
// The generated test for "method" in tests class
$this->assertEquals('expectation string', $this->method(1, 2, 'a string'));
$this->assertTrue($this->method(4, 5, 'another'));
$this->AssertEquals(null, $this->method());
$this->assertNull($this->method());
<?php
// The class to test content
/** @PHPUnitGenGet() */
/** @PHPUnitGenSet() */
Those two annotations will allow you to auto-generate tests for simple getter / setter. Your getter / setter needs to be named like the following:
get<MyProperty>() {}
set<MyProperty>() {}
PHPUnit Generator has an "auto" option: If you activate it, it will search for the property when it find a method beginning with "get" or "set", and if the property exists, it will generate tests.
If the method to test is private or protected, PHPUnit Generator will access the method with PHP ReflectionClass.
UnitGenerator needs the following components to run: