我试图通过测试使用zend expressive构建的rest api控制器来学习PHPUnit,但在网上找不到任何关于如何执行相同操作的资源。Zend 框架的官方文档中的代码不适用于 zend expressive。所以我尝试遵循PHPUnit 文档。
这是我现在所做的: -
use App1\Api\AccountApi;
use PHPUnit\Framework\TestCase;
use PHPUnit\DbUnit\TestCaseTrait;
class AccountTest extends TestCase {
use TestCaseTrait;
static private $pdo = null;
private $conn = null;
public function setUp(){
/* Avoiding truncate operation of getDataSet() since we are trying to access view and not a table from database. */
}
public function getConnection() {
if ($this->conn === null) {
if (self::$pdo == null) {
self::$pdo = new PDO('mysql:host=localhost;dbname=workflow','root', 'root');
}
$this->conn = $this->createDefaultDBConnection(self::$pdo, ':host=localhost;dbname=workflow');
}
return $this->conn;
}
public function getDataSet()
{
$dataset = $this->getConnection()->createDataSet();
return $dataset;
}
public function testIndexAction()
{
$api = new AccountApi();
$response = $api->indexAction(); // Invokes a findAll() operation in the model which basically does a 'select * from workflow.account'
print $response; // to see if a response is returning
}
}
但是当我运行上面的代码时,它会抛出这个错误:
1) AgentTest::testIndexAction
Zend\Db\Adapter\Exception\RuntimeException: Connect Error: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is k
nown.
C:\webserver\GIT\gco3api\vendor\zendframework\zend-db\src\Adapter\Driver\Pdo\Connection.php:283
C:\webserver\GIT\gco3api\vendor\zendframework\zend-db\src\Adapter\Driver\Pdo\Pdo.php:255
C:\webserver\GIT\gco3api\vendor\zendframework\zend-db\src\Sql\Sql.php:138
C:\webserver\GIT\gco3api\src\Core\src\Abstracts\Model.php:453
C:\webserver\GIT\gco3api\src\Core\src\Abstracts\Model.php:422
C:\webserver\GIT\gco3api\src\App1\src\Api\AccountApi.php:28
C:\webserver\GIT\gco3api\test\AppTest\App1\AccountTest.php:52
我真的不知道我使用 PHPUnit 测试 rest api 控制器的方法是否正确,因为我是 php 和 phpunit 的新手。我将不胜感激任何帮助指出我正确的方向。