我有一个 Domoticz 类,该类读取外部API。
class Domoticz extends HeaterService implements DomoticControllerInterface {
public function getFromApiCurrentHeaterStatus($current_heater)
{
$current_heater = json_decode($current_heater);
if (!isset($current_heater->result)) {
throw new \Exception('There is a problem retrieving heater status');
}
$heater = array();
foreach ($current_heater->result as $result) {
$heater['idx'] = (int)$result->idx;
$heater['status'] = $result->Status;
}
return $heater;
}
}
方法getFromApiCurrentHeaterStatus
返回一个数组。
这是我的考验
class DomoticzTest extends TestCase
{
/**
* This is a copy of real json got from an API call
*/
private $heater_answer = '{"result":{"2":{"Status":"Off","idx":"17"}}}';
/**
* Test that from an answer as $heater_answer, we can get an array with idx and status
*
*/
public function testThatWeCanGetAnArrayFromHeaterAnswer()
{
$right_heater_array = array('idx' => 17, 'status' => 'Off');
$right_array_we_want = $right_heater_array; // we need to get an array
$wrong_heater_array = array('idx' => 11, 'status' => 'On');
$wrong_array_we_dont_want = $wrong_heater_array;
$mock = $this->getMockBuilder('\App\Libs\Domoticz')
->disableOriginalConstructor()
->getMock();
$mock
->expects($this->once())
->method('getFromApiCurrentHeaterStatus')
->with($this->heater_answer)
->willReturn($right_array_we_want);
$heater = $mock->getFromApiCurrentHeaterStatus($this->heater_answer);
$this->assertEquals($right_array_we_want,$heater);
}
测试通过。实际上,通过“真实” API调用($this->heater_answer
),我们得到了一个数组
$heater['idx'] = 17;
$heater['status'] = 'Off';
现在,我确实尝试更改属性heater_answer
,在每次测试通过的情况下,都将idx从17更改为2,例如status。
换句话说:真正的方法不执行吗?如何强制测试执行真正的真实方法?
答案 0 :(得分:1)
为什么要嘲笑它?您没有在该方法中进行实际的API调用。
由于您正在测试方法是否将实际的加热器答案解码为正确的格式,因此测试应如下所示:
private $heater_answer = '{"result":{"2":{"Status":"Off","idx":"17"}}}';
public function testThatWeCanGetAnArrayFromHeaterAnswer()
{
$mock = $this->getMockBuilder('\App\Libs\Domoticz')
->setMethodsExcept(['getFromApiCurrentHeaterStatus'])
->disableOriginalConstructor()
->getMock();
$response = $mock->getFromApiCurrentHeaterStatus($this->heater_answer);
$this->assertEquals([
'idx' => 17,
'status' => 'Off'
], $response);
}
通过添加setMethodsExcept()
,该数组中定义的方法将不会被测试双精度代替。然后,您可以实际对其进行测试。