pbweb / mimic
功能测试的模拟类
Requires
- php: >=8.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^10.5
README
此库可用于创建类的模拟,这些模拟可用于(功能)测试。
模拟类类似于phpunit中的带有存根方法的模拟对象,但在功能层面上。
安装
使用composer安装
使用composer安装mimic
composer require pbweb/mimic
示例
假设你有一个客户端类,该类与外部REST服务通信。其接口可能如下所示
interface RestClient { public function get($something); public function put($something); }
现在,在(功能)测试中使用真正连接到REST服务器的类是一个坏主意,因为该服务器可能不在你的测试范围内,并可能影响测试结果。
要创建模拟客户端,你需要像这样扩展MimicActionHandler
class MimicRestClient extends MimicActionHandler implements RestClient { public function get($something) { return $this->handleAction(__FUNCTION__, func_get_args()); } public function put($something) { return $this->handleAction(__FUNCTION__, func_get_args()); } }
现在你可以在测试中模拟RestClient
的行为
// In your dependency injection container: $mimicClient = new MimicRestClient(); // In your test setup: $mimicClient->enqueue('get', ['cheese'], 'cheese result'); // In your test or in a class which you are testing: $result = $mimicClient->get('cheese'); // returns 'cheese result'
参数匹配器
如果你想要更精细地控制对调用期望的参数,你可以使用参数匹配器。
ArgumentMatchers
类实例化了一些匹配器,可以将这些匹配器传递给enqueue的期望参数列表。
// Matches any call to update that has 1 as its first argument and any value as its second argument. $mimicClient->enqueue('update', [1, ArgumentMatchers::any(), 'result');
用法
扩展MimicActionHandler
将允许你的类拥有模拟enqueue系统。你想模拟的每个方法都应该有这个作为主体
return $this->handleAction(__FUNCTION__, func_get_args());
请参阅tests/Service/SampleMimic
以获取示例。
enableQueue
$mimic->enableQueue();
enableQueue
将启用队列的使用。
disableQueue
$mimic->disableQueue();
disableQueue
将停止使用队列。
isQueueEnabled
$isQueueEnabled = $mimic->isQueueEnabled();
isQueueEnabled
将返回一个布尔值,表示队列的状态。
enqueue
$mimic->enqueue($method, array $argumentList = [], $response = null, $throw = false);
enqueue
将方法调用添加到期望队列。你可以添加任意多的方法预测。如果下一个对模拟的调用是期望的调用,则将返回给定的响应,并将其从队列中删除。如果下一个对模拟的调用不是添加到队列中的期望调用,则将抛出异常。
如果你将throw
设置为true
,则将抛出响应而不是返回。
getQueueContent
$actionList = $mimic->getQueueContent();
getQueueContent
将返回所有已添加到队列中的剩余操作作为Action模型。有关模型的信息,请参阅Action
类。
isFinished
$isFinished = $mimic->isFinished();
isFinished
将返回true,如果队列中没有剩余的操作。否则返回false。
clearQueue
$mimic->clearQueue();
clearQueue
将删除队列中所有剩余的操作。