Mocking 嘲弄:测试是成功的,但它是错误的

Mocking 嘲弄:测试是成功的,但它是错误的,mocking,phpunit,mockery,Mocking,Phpunit,Mockery,我有一个Domoticz类,它读取外部API class Domoticz extends HeaterService implements DomoticControllerInterface { public function getFromApiCurrentHeaterStatus($current_heater) { $current_heater = json_decode($current_heater); if (!isset($cur

我有一个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);
}
考试通过了。实际上,通过“real”API调用(
$this->hearter\u answer
),我们得到了一个数组

$heater['idx'] = 17;
$heater['status'] = 'Off';
现在,我确实尝试更改属性
heater\u answer
,例如,将idx从17更改为2,或者更改状态,在每种情况下测试都通过


换句话说:真正的方法是它没有被执行吗?我怎样才能强制测试执行真正的方法呢?

你为什么要嘲笑它?您没有在该方法中进行实际的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);
}

通过添加
setMethodsCept()
,该数组中定义的方法将不会被测试双精度替换。然后你就可以测试它了

我之所以模仿,是因为uu construct()(例如)初始化API调用(user/passw/token)等,所以我不能使用原始构造函数。