我終於進入PHP單元測試(總好過從來沒有耶!)模擬類PHPUnit中
我有一個Utility
類做了一些事情,包括認證用戶的對web服務的訪問。 Utility::authenticate
方法需要一個Settings
對象,其中包含由authenticate
檢查的用戶名等。
所以在我的測試中,我嘲笑一個Settings
對象是這樣的:
$settings = $this->getMock('Settings', array('getSettings'));
$settings->method('getSettings')
->willReturn([
'USERNAME' => 'testuser',
'SERVER' => 'testserver'
]);
$mock = $settings->getSettings();
到目前爲止好,但是當我試圖嘲弄對象傳遞給authenticate
它拋出一個錯誤:
$this->assertEquals($testvalue, Utilities::authenticate($settings));
Argument 1 passed to Utilities::authenticate() must be an instance of Settings, instance of Mock_Settings_d0361624 given
如何模擬Settings
對象,使其看起來像Utilities
類的「真實」對象?
編輯添加的getSettings功能:
class Settings {
private $settings;
private static $instance;
public function __construct(){
$configfile = "config/config.ini";
//if(!$this->settings = parse_ini_file($configfile, true)){
//die('SETTINGS OBJECT NOT FOUND OR COULD NOT BE PARSEd');
//}
}
/**
* @return Settings
*/
public static function getSettings(){
if (!self::$instance){
self::$instance = new Settings();
}
if(!utilities::authenticate(self::$instance)) die('AUTHENTICATION FAILED-- CHECK API KEY');
return self::$instance;
}
您可以發佈測試方法的代碼? – Matteo