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