folsh / phpunit-dynamic-fixture
动态setUp,在测试中创建合适的上下文
0.2.0
2014-08-25 21:40 UTC
Requires (Dev)
- phpunit/phpunit: >=3.7@stable
This package is not auto-updated.
Last update: 2024-10-02 09:49:28 UTC
README
DynamicFixture
得益于注解,这个库允许你在每个测试之前调用动态/自定义的"setUp"方法。这使你的测试更容易理解,因为你明确设置了将使用的上下文/变量。它还可以加速你的测试,因为只需初始化所需的内容。
安装
Composer
只需将此添加到你的composer.json
文件中
"require": { "folsh/phpunit-dynamic-fixture": "dev-master" }
然后运行php composer.phar install
PhpUnit配置
要激活插件,将监听器添加到你的phpunit.xml(.dist)文件中
<?xml version="1.0" encoding="UTF-8"?> <phpunit> ... <listeners> <listener class="folsh\DynamicFixture\DynamicFixtureListener" file="vendor/folsh/phpunit-dynamic-fixture/src/DynamicFixtureListener.php" /> </listeners> </phpunit>
使用方法
使用注解"@setUpContext"在测试前调用指定的方法。当然,你可以添加任意数量的注解。
class MyTest extends PHPUnit_Framework_TestCase { private $name; /** * Must be public */ public function setUpName() { $this->name = 'Nicolas'; } public function initContext() { //... } /** * @setUpContext setUpName * @setUpContext initContext * @setUpContext ... * */ public function testSetUpName() { //$this->name is "Nicolas" } }
参数
如果你想在函数中添加一些参数,请将它们放在括号之间。警告:目前,你只能添加简单类型(见示例)接受的类型
- string
- json
- array (单层)
- numeric (转换为字符串!)
class MyTest extends PHPUnit_Framework_TestCase { private $name1; private $name2; private $list; /** * Must be public */ public function setUpNames($name1, $name2) { $this->name1 = $name1; $this->name2 = $name2; } public function initContext() { //... } /** * @setUpContext setUpNames("Nicolas", "Cedric") */ public function testSetUpNames() { //$this->name1 is "Nicolas" //$this->name2 is "Cedric" } }
class MyTest extends PHPUnit_Framework_TestCase { private $list; /** * Must be public */ public function setUpArray(array $list) { $this->list = $list; } public function initContext() { //... } /** * @setUpContext setUpArray(["Nicolas", "Cedric"]) */ public function testSetUpArray() { //$this->list is array("Nicolas", "Cedric") } }
自定义
如果你不喜欢注解的名称,可以通过在构造函数中传递一个新的名称来更改它
<listener class="folsh\DynamicFixture\DynamicFixtureListener" file="vendor/folsh/phpunit-dynamic-fixture/src/DynamicFixtureListener.php"> <arguments> <string>myCustomSetUp</string> </arguments> </listener>