首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嘲弄/单位:测试是成功的,但它是错误的

嘲弄/单位:测试是成功的,但它是错误的
EN

Stack Overflow用户
提问于 2019-01-24 12:17:02
回答 1查看 62关注 0票数 0

我有一个Domoticz类,它读取外部API。

代码语言:javascript
复制
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返回一个数组。

这是我的测试

代码语言:javascript
复制
    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),我们可以得到一个数组

代码语言:javascript
复制
$heater['idx'] = 17;
$heater['status'] = 'Off';

现在,我确实尝试更改属性heater_answer,例如将idx从17更改为2,或者在任何情况下都会通过测试。

换句话说,真正的方法是它没有执行吗?如何才能强制测试真正执行真正的方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-24 14:21:24

你为什么要嘲笑它?您没有在该方法中进行实际的API调用。

由于您正在测试您的方法是否正在将实际的加热器答案解码为正确的格式,所以您的测试应该如下所示:

代码语言:javascript
复制
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(),该数组中定义的方法将不会被test替换。然后你就可以测试它了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54346505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档