1)当测试的东西,它与API包装器一起工作时,应该模拟整个API包装类,并模拟抛出异常作为错误状态和测试,应用程序本身将如何对这些异常做出反应。
它应该停止做一些依赖于API响应的操作,它应该可能会显示一些用户友好的错误。更有甚者,您可以(也可能应该)测试API包装器上的哪些方法被调用了+多少次以及传递了哪些参数。
<?php
public function testShowUser() {
$fb = $this->getMock('Facebook\Api');
$fb->expects($this->once()) // if your library will call getUserInfo() more than once or never, the test will fail
->method('getUserInfo')
->with($this->equalTo('johndoe')) // if the method will be called with different parameter, the test will fail
->will($this->throwException('Facebook\NonExistingUser'));
$myApp = new MyApp($fb);
$myApp->renderUser('johndoe'); // if this will throw uncaught exception, the test will fail
$this->assertEquals(
array('The user you requested does not exist'),
$myApp->getFlashMessages()
);
}
2)当测试的API包装本身你可以模拟从API原始响应。
您应该围绕HTTP通信整体的东西分开,一些特定的类(卷曲包装/有自己的单元测试/),并假设服务器返回的一些特定的HTTP代码和响应。
您可以将所有可能的响应类型保存在文件中,以便您可以将它们加载到测试中作为响应。
我建议做这种方式:
<?php
/**
* @expectedException Facebook\NonExistingUser
*/
public function testUnavailableApi() {
$curl = $this->getMock('CurlWrapper');
$curl->expects($this->once())
->method('getBody')
->will($this->returnValue(file_get_contents('fb_404_response.json')));
$curl->expects($this->once())
->method('getStatusCode')
->will($this->returnValue(404));
$api = new Facebook\Api($curl);
$api->getUserInfo('johndoe');
}
所以你想实现假的API来测试你的代码?我对吗? – 2012-08-31 11:37:42
这是正确的。 – Luigi 2012-08-31 14:02:15