codecept教程-php单元测试框架
1、下载codecept.phar
wget http://codeception/codecept.phar
2、安装,生成运行时目录结构
php codecept.phar bootstrap
执行后会生成对应的目录和配置。
codeception.yml是配置文件。可以设置测试过程中的输出路径,数据库信息等。
tests/_bootstrap.php是运来加载要测试的类,导入而不运行。
比如yii框架可以把入口文件中index.php中的代码写进来,但是一定不要让框架运行,就是去掉Yii::$app->createWebApplication()->run();中的->run();
3、创建单元测试
php codecept.phar generate:test unit Hello
运行后会生成tests/unit/HelloTest.php文件:
在文件中加入Assert进行断言测试
<?php
class HelloTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
protected function _before()
{
}
protected function _after()
{
}
// tests
public function testMe()
{
$this->assertTrue(true, \Yii::app()->db->createCommand('show tables')->queryAll());
$this->assertInternalType('array', \Yii::app()->db->createCommand('show tables')->queryAll());
}
}
执行写好的测试案例:
php codecept.phar run unit
成功则显示:
Codeception PHP Testing Framework v2.2.10
Powered by PHPUnit 5.7.17 by Sebastian Bergmann and contributors.
Unit Tests (1) -------------------------------------------------------------------------------------------------------------------------------------------------
+ HelloTest: Me (0.05s)
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Time: 410 ms, Memory: 14.50MB
OK (1 test, 2 assertions)
生成报表输出(支持json,html,xml,这里用json):
php codecept.phar run unit --json
...
OK (1 test, 1 assertion)
- JSON report generated in file://D:\svn\xqsj_dev\main\tests/_output\report.json
4、例子
通常断言失败时就会退出这个测试方法,使用specify这个特性可以使得断言失败时不会退出,先看例子:
class HelloWorldTest extends \Codeception\TestCase\Test{
use \Codeception\Specify; //要先在这里use一下
public function testDemo(){
$this->specify('环节1:测试time函数', function(){
//断言失败了不会往这个函数的代码下面跑而已,但外面还是会继续往下跑的
$this->assertInternalType('string', time()); //失败
$this->assertInternalType('string', md5(time())); //成功,但上面失败,跑不到这里,退出这一次的specify
});
//无论上面的specify里成还是败都还会继续跑这里
$this->assertTrue(true);
$this->specify('环节2:测试date函数', function(){
$testTimeStamp = 1447171200;
$this->assertNotEquals(1990, date('Y', $testTimeStamp));
$this->assertEquals(2015, date('Y', $testTimeStamp));
$this->assertEquals(5, count(explode('-', date('Y-m-d')))); //失败
});
$this->assertTrue(false, '外面也失败了');
}
}
使用
this−>specify(′测试目标的说明′,
具体的测试工作代码函数)
可以实现一块specify中断不会导致specify外面的测试代码中断而只会中断specify里面的代码而已,这种情况在复杂业务测试时,当一个测试方法中的两个测试逻辑没有依赖关系时比较有用,而且这里还有一个说明的作用,将一大块代码进行一个说明,但这样说不是算完美,不过specify是比较有用的,只是小规模测试时一般用不上。
6、验收测试部分
1.创建验收测试文件
php codecept.phar generate:cept acceptance IndexPage
在tests/ acceptance.suite.yml中配置url为你需要的字段。
class_name: AcceptanceTester
modules:
enabled:
- PhpBrowser:
url: http://localhost/myapp
- \Helper\Acceptance
在tests/acceptance/_bootstrap.php中写入要加载的类,相当于autoload.php
在\tests\acceptance\IndexPageCept.php中写测试用例:
更多推荐
codecept教程-php单元测试框架
发布评论