3

我正在POST向控制器的操作发送一些数据。该动作与一些 json 编码的字符串相呼应。我想验证该操作的 json 编码字符串是否符合我的要求。我想知道我怎样才能得到那个字符串?

我的测试如下所示:

$this->request->setMethod('POST')
     ->setPost(['test' => 'databaseschema_Database']);

$params = ['action' => 'analysis', 'controller' => 'Index', 'module' => 'default'];
$urlParams = $this->urlizeOptions($params);
$url       = $this->url($urlParams);
$result    = $this->dispatch($url);

$this->assertJsonStringEqualsJsonString(
    $result, json_encode(["status" => "Success"])
);

我的测试失败,我收到以下消息:

1) IndexControllerTest::testAnalysisAction
Expected value JSON decode error - Unknown error
stdClass Object (...) does not match expected type "NULL".

谁能指导我如何做到这一点?

4

1 回答 1

0

If you want to do unit testing, what you really want to do is extract the json encoding into it's own class (or a method inside a utils class or something) and then test those method instead of your whole controller.

The problem with your approach is that when running phpunit, there is not $_POST array. The code above does not show what is happening, but I guess there is different behaviour when run through apache and cli which causes your test to fail.

I would create a TransformerClass and test this in isolation:

class JsonTransformer
{
    public function transformPostData(array $postArray)
    {
        // transformation happening
    }
}

class JsonTransformerTest extends \PHPUnit_Framework_TestCase
{
    public function testTransformPostData()
    {
        $transformer = new JsonTransformer();
        $data = array('action' => 'analysis', 'controller' => 'Index', 'module' => 'default');
        $result = $transformer->transformPostData(data);

        $this->assertJsonStringEqualsJsonString($result, json_encode(array("status" => "Success")));
    }
}

If you need to test your whole request/response, you would use some kind of HTTPClient, request the url, send the post data and see if the response is what you'd expect.

Everything in between (like faking the post data) leaves you with more problems and more code to maintain than it does you good.

于 2013-03-01T11:31:35.677 回答