Yii2 使用 codeception

测试过程

1、保证项目composer.json的require-dev中含有

 "codeception/base": "^2.2.3",
 "codeception/verify": "~1.0.0"

如果没有,请添加然后执行composer update

2、进入到你的应用中,比如common,
创建模板suite,执行../vendor/bin/codecept init unit

> This will install Codeception for unit testing only

? Where tests will be stored? (tests)  ../tests/common#1 这里输入测试文件路径,目的是将测试代码独立出来
? Enter a default namespace for tests (or skip this step) tests\common  #2 这里输入一个命名空间

Codeception provides additional features for integration tests
Like accessing frameworks, ORM, Database.
? Do you wish to enable them? (y/n) y #3 这里回答y
> Unit helper has been created in tests/_support/Helper
> UnitTester actor has been created in tests/_support
> Actions have been loaded
> Created test directory inside at tests

 INSTALLATION COMPLETE 

Unit tests will be executed in random order
Use @depends annotation to change the order of tests
To access DI, ORM, Database enable corresponding modules in codeception.yml
Use $this->tester object inside Codeception\Test\Unit to call their methods
For example: $this->tester->seeInDatabase('users', ['name' => 'davert'])

Next steps:
Create the first test using codecept g:test unit MyTest
Run tests with codecept run
Happy testing!

3、必要的配置:
common/config/test-local.php:

 [
            'db' => [
                'dsn' => 'mysql:host=localhost;dbname=yii2advanced_test', //修改你的测试数据库
            ]
        ],
    ]
);

common/config/test.php:

 'app-common-tests',
    'basePath' => dirname(__DIR__),
    'components' => [
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'common\models\User',
        ],
        'request' => [
            'class' => '\yii\web\Request',
            'enableCookieValidation' => false,
        ],
    ],
];

common/codeception.yml修改为:

namespace: tests\common
suites:
    unit:
        path: unit
        actor: UnitTester
    api:
        path: api
        actor: ApiTester
modules:
    config:
        Yii2:
            configFile: 'config/test-local.php' #加载Yii2配置文件,必须
settings:
    bootstrap: _bootstrap.php #加载Yii2,必须
    shuffle: true
    lint: true
paths:
    tests: ../tests/common
    output: ../tests/common/_output
    support: ../tests/common/_support
    data: ../tests/common
coverage:
   enabled: true
   whitelist:
        include:
            - components/* #需要测试的代码

需要支持Yii2,且需要在tests/common下新建_bootstrap.php:

4、新建测试suite:
执行../vendor/bin/codecept g:suite unit../vendor/bin/codecept g:suite api

5、新建测试:
执行../vendor/bin/codecept g:test unit FirstUnit或者../vendor/bin/codecept g:cest api FirstApi
然后在tests/common/unit/FirstUnitTest.php或者tests/common/unit/FirstApiCest.php中编写测试代码

6、执行../vendor/bin/codecept run --coverage-html,打开tests/webserver/_output/coverage/index.html打开看到覆盖率。

你可能感兴趣的:(Yii2 使用 codeception)