我们如何在测试中使用字符串替换和变量?我怀疑这很常见,我根本不知道在哪里看。示例测试:
$I = new ApiTester($scenario);
$I->wantTo('Get Stuff');
$I->amHttpAuthenticated('myuser', 'mypass');
$I->haveHttpHeader('Content-Type', 'application/json');
$I->haveHttpHeader('Custom-Header', 'friendlycorp');
$I->sendGet('/a/path/that/contains/variables');
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
正在测试的每个REST API位置使用不同的值,并且URL也会根据要测试的服务而更改。所以,也许是这样的:
$I->amHttpAuthenticated('{USERNAME}', '{PASSWORD}');
$I->sendGet('/a/path/{SERVICE_ID}/and/{SOMETHING_ELSE}/and/such');
$I->haveHttpHeader('Custom-Header', '{SERVICE_ID}');
我希望配置文件可以定义{SERVICE_ID}和{FUNCTION}之类的内容,具体取决于我正在测试的REST API服务位置以及其他变量。例如:
FriendlyCorp:
SERVICE_ID: friendlycorp
SOMETHING_ELSE: foo
USERNAME: myuser
PASSWORD: mypass
OpenExample:
SERVICE_ID: openexample
SOMETHING_ELSE: bar
USERNAME: myuser2
PASSWORD: mypass2
然后在执行代码时,我会选择针对FriendlyCorp或OpenExample运行测试,并且会在测试中使用所述值。
答案 0 :(得分:5)
/**
* @example { "service_id": "friendlycorp", "something_else": "foo", "username": "myuser", "password": "mypass" }
* @example { "service_id": "openexample", "something_else": "bar", "username": "myuser2", "password": "mypass2" }
*/
public function services(ApiTester $I, \Codeception\Example $example)
{
$I->amHttpAuthenticated($example['username'], $example['username']);
$I->haveHttpHeader('Content-Type', 'application/json');
$I->haveHttpHeader('Custom-Header', $example['service_id']);
$I->sendGet("/a/path/{$example['service_id']}/and/{$example['something_else']}/and/such");
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
}