gpt4 book ai didi

unit-testing - 针对早期返回进行测试(防御性编程)

转载 作者:行者123 更新时间:2023-11-28 21:09:31 24 4
gpt4 key购买 nike

我正在学习测试并尝试使用“提前返回”来测试功能。函数成功时会在另一个类中设置一个属性,失败时只会返回,因此在这两种情况下它都会“返回”void。

class Test
{
private $fileHandler;
private $config;

public __constructor($fileHandler, $config)
{
$this->fileHandler = $fileHandler;
$this->config = $config;
}

public function example($filePath)
{
$exists = $this->fileHandler->exists($filePath);

if ($exists === false) {
return;
}

$this->config->set($filePath);
}
}

在这个例子中,我相信我可以通过两个单元测试和模拟 fileHandler 类来测试它。

对于失败(提前返回),不应调用 $config 类的方法 set(),而对于成功,则应调用该方法。

但是,如果我尝试将 never() 更改为 once(),那么这个测试就会通过,这让我觉得整个测试都是假的。

/** test */
public function config_is_not_set_with_missing_file()
{
$fileHandlerMock = $this->getMockBuilder(fileHandler::class)->getMock;
$fileHandlerMock->method('exists')
->willReturn('false');
$configMock = $this->getMockBuilder(config::class)->getMock;

$test = new Test($fileHandlerMock, $configMock);
$test->example('fake file path');

$configMock->expects($this->never())
->method('set');
}

最佳答案

您的文件处理程序 mock 正在返回字符串 'false',即 !==false。将其更改为 false 并且 Tets::example 应该提前返回。

关于unit-testing - 针对早期返回进行测试(防御性编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38656535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com