1

そのようなメソッドをテストする方法:

public function add() {
if (!empty($this->request->data)) {
        $this->Contest->create();

        if ($this->Contest->saveAll($this->request->data)) {


            $contestStage['name'] = 'First - ' . $this->request->data['Contest']['name'];
            $contestStage['contest_id'] = $this->Contest->id;

            if ($this->Contest->ContestStage->save($contestStage)) {
                $this->setMessage(__ADD_OK, 'Konkurs');
                $this->redirect(array(
                    'action' => 'view',
                    $this->Contest->id
                ));
            } else {
                $this->setMessage(__ADD_ERROR, 'Konkurs');
            }
        } else {
            $this->setMessage(__ADD_ERROR, 'Konkurs');
        }
    }
}

私のテスト方法:

public function testAdd() {
        $this->generateWithAuth(self::ADMIN); // genereting controller here
        $url = $this->getUrl('add');
        $options2 = array(
            'method' => 'post',
            'data' => array(
                'Contest' => array(
                    'id' => 3,
                    'owner_id' => 1,
                    'name' => 'Testing',
                    'created' => '2012-11-16 12:02:33.946',
                ),
            ),
            );
        $this->testAction($url, $options2); 
        $this->assertArrayHasKey('Location', $this->headers, 'No redirection');
        $this->assertEquals($this->Contest->hasAny(array('Contest.name' => 'Testing')), true);    
        $messages = Set::extract('{flash}.message', CakeSession::read('Message'));
    }

私が受け取るものは

PDOEXCEPTION
SQLSTATE[23505]: Unique violation: 7 BŁĄD: double key value violates a constraint

     uniqueness "contest_stages_pkey" DETAIL: キー (id)=(1) は既に存在します。

それは本当なので、私はid = 1のcontestStageを持っているのに、なぜ次のものを使用しないのですか; <

4

1 に答える 1

0

Cakephp がそれをうまくテストする方法を文書化していないのはちょっと奇妙です。

問題は、コンテスト ID を 2 回挿入することです。使用しているデータベースにテスト プレフィックス (または好きなもの) があることを確認し、テスト テーブルをクリアする必要があります。

別の方法として、代わりにフィクスチャを使用することもできます。データは事前​​にデータが入力されるため、はるかに優れたテストケースが生成されるため、いつでもデータベースに何があるかがわかります。それでも必ずプレフィックスを使用してください。私はそれをしないという間違いを一度犯し、毎回データベース全体を吹き飛ばしました

幸運を

于 2013-03-29T05:33:34.243 に答える