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 に答える