微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于JSON输出的PHPUnit测试

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

我测试的方法是:

/**
 * @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 by Sebastian Bergmann.

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"}]..

Time: 0 seconds, Memory: 10.25Mb

There was 1 failure:

1) CategoryTest::testGetCategory Failed asserting that null is not
null.

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

解决方法:

你的getCategory()函数回应了一些东西:

echo json_encode($data);

但它不会返回任何东西.
因此,$json变量在测试中将为null.

您可能想要在函数末尾返回值:

return json_encode($data);

要测试输出,您需要在测试中使用expectOutputString()或expectOutputRegex()方法.为了测试非空输出,我相信以下应该做:

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

有关如何断言输出的详细信息,请参见phpunit documentation.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐