php - 如何使用 PHPUnit 测试此方法调用?

标签 php unit-testing testing phpunit

待测代码:

// Add the activation provider argument to the factory definition
$factoryDefinition = $container->getDefinition('gremo_subscription_factory');
$factoryDefinition->addArgument(new Reference($providerId));

测试方法应该检查addArgument 方法,包括$providerId 参数。我刚刚学习 PHPUnit,现在我只能调用 $this->anything():

$container->expects($this->at(3))
    ->method('getDefinition')
    ->with('gremo_subscription_factory')
    ->will($this->returnValue($factory));

$factory->expects($this->once())
    ->method('addArgument')
    ->with($this->anything());

$this->pass->process($container);

如何检查参数类型是否为 Reference 类,并且(反过来)它的参数恰好是字符串 $providerId

最佳答案

这非常复杂,特别是因为 Reference 类不是依赖注入(inject)的,而且方法调用不会返回任何内容。但是,我认为您可以使用 argument constraints 绕过它.下面是我将如何处理第二个子句:

$factory->expects($this->once())
    ->method('addArgument')
    ->with($this->logicalAnd(
        $this->isInstanceOf('Reference'),
        $this->attributeEqualTo('attribute', $providerId)
    ));

logicalAnd() 中的第二项基本上只是检查创建的 Reference 对象,以查看是否正确分配了 $providerId (我不确定 Reference 构造函数中的 $providerId 会发生什么,但我假设它被保存到实例变量或其他东西中)。

然而,这类事情正在进入测试 Reference 类的实现细节的领域,因此像这样的测试对于维护 SRP 不是很好。通过重构代码可以更好地解决所有这些问题。一般来说,如果很难测试,那可能不是测试套件的错。如果可以,请考虑首先为此做出更改,而不是编写过于聪明的测试。

关于php - 如何使用 PHPUnit 测试此方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13871386/

相关文章:

Python 在运行测试时导入 src 模块

jquery - Selenium:根据兄弟元素文本选择元素

php - 检查字符串中是否存在星号

php - 我的 sql 查询不能完全工作

python - 在python的unittest中,如何模拟其中包含伪造图像的伪造文件夹?

python - 如何在 Python3 中使用构造函数模拟对象?

java - 如何改进 WebDriver ExpectedCondition 的错误消息?

testing - 在 TestCafe 中等待 'WebComponentsReady' 事件的最佳方法是什么?

php - TCPDF 是否支持字距调整?

php - 使用CSS创建水平树