5

为什么我不能获取输入并测试它是否不为空?

我正在测试的方法:

/**
 * @method: getCategory
 * retrieves the categories
 * @return json category data
 */
public function getCategory() {

    $cat = $this->em->getRepository('Entities\Category')->findAll();
    $data = array();
    foreach ($cat as $res) {
        $data[] = array(
            'catId' => $res->__get('catId'),
            'category' => $res->__get('category'),
            'item' => $res->__get('item')
        );
    }
    echo json_encode($data);
}

我的测试:

 /**
 * @covers Category::getCategory
 * @todo   Implement testGetCategory().
 */
public function testGetCategory() {
    $json = $this->object->getCategory();
    $this->assertNotNull($json);
}

错误消息,它返回一个 JSON 对象数组:

塞巴斯蒂安伯格曼的 PHPUnit 3.7.8。

F[{"catId":1,"category":"FLORALS2","item":"RED ROSES"}, {"catId":2,"category":"TENTS","item":"12X14"}, {"catId":3,"category":"FLORAL","item":"WHITE ROSES"}, {"catId":4,"category":"TENTS","item":"15X24"}, {"catId":5,"category":"CHAIRS","item":"BLACK CHAIR"}, {"catId":6,"category":"CHAIRS","item":"RED CHAIRS"}, {"catId":7,"category":"TENTS","item":"23X23"}, {"catId":8,"category":"CANDLES","item":"RED CANDLES"}, {"catId":9,"category":"CANDLES","item":"WHITE CANDLES"}, {"catId":10,"category":"CANDLES","item":"BLACK CANDLES"}, {"catId":11,"category":"CANDLES","item":"ORANGE CANDLES"}, {"catId":12,"category":"TABLE","item":"4X8 TABLE"}, {"catId":13,"category":"DRAPERYS","item":"24\" WHITE LINEN"}, {"catId":14,"category":"LINEN","item":"WHITE CURTAINS"}, {"catId":17,"category":"DRAPERY","item":"SILK TABLE CLOTH"}, {"catId":18,"category":"FLORAL","item":"ORANGE DAISIES"}]..

时间:0秒,内存:10.25Mb

有 1 次失败:

1)CategoryTest::testGetCategory断言 null 不为 null 失败。

/var/www/praiseDB/tests/controller/CategoryTest.php:42

4

1 回答 1

7

您的 getCategory() 函数呼应了一些东西:

echo json_encode($data);

但它不返回任何东西。因此, $json 变量在您的测试中将为空。

您可能打算在函数末尾返回值:

return json_encode($data);

要测试输出,您需要在测试中使用 expectOutputString() 或 expectOutputRegex() 方法。要测试非空输出,我认为应该执行以下操作:

/**
 * @covers Category::getCategory
 * @todo   Implement testGetCategory().
 */
public function testGetCategory() {
    $this->expectOutputRegex('/./');
    $this->object->getCategory();
}

有关如何断言输出的详细信息,请参阅phpunit 文档。

于 2013-05-01T21:37:28.693 回答