PHPUnit:使用模具响应测试RestFul API

时间:2015-06-21 07:44:42

标签: php json api zend-framework2 phpunit

我正在尝试PHPUnit在我的ZF2项目中测试一个动作。

API使用die($jsonObject)返回JSON字符串。

这导致PHPUnit测试停止处理并且只是死于JSON响应。

public function testStartupAction() {

    $this->dispatch('/api/v3/startup', "POST", array());

    $this->assertJson('{"status":false,"message":"Please enter the UID","data":null}');

}

assetJson方法永远不会到达。

PHPUnit输出:

PHPUnit 4.7.3 by Sebastian Bergmann and contributors.
..{"status":false,"message":"Please enter the UID","data":null}

PHPUnit如何继续测试,以便得到结果?

1 个答案:

答案 0 :(得分:2)

我强烈建议尝试在重写代码中找到解决方案,以便在控制器中返回JSON字符串。使用sqlsrv返回响应对象不是最佳选择。

如何从控制器操作返回JSON的示例可以简单如下:

"dblib:host=$this->serverName:$this->port;dbname=$this->db"

其中$ data是您的数据数组。结果将自动更改为JSON字符串。

这也将解决您的测试问题。