我有一个使用 ServiceB 的 ClassA。在某些情况下,类 A 最终应该不会调用任何 ServiceB 方法。我现在想测试一下,确实没有调用任何方法。
这可以按如下方式完成:
$classA->expects( $this->never() )->method( 'first_method' );
$classA->expects( $this->never() )->method( 'second_method' );
...
有没有办法简单地声明"不应在此对象上调用任何方法",而不必为每个方法指定限制?
是的,这很简单,试试这个:
$classA->expects($this->never())->method($this->anything());
您可以使用方法 MockBuilder::disableAutoReturnValueGeneration
。
例如,在测试中覆盖默认TestCase::getMockBuilder
:
/**
* @param string $className
* @return MockBuilder
*/
public function getMockBuilder($className): MockBuilder
{
// this is to make sure, that not-mocked method will not be called
return parent::getMockBuilder($className)
->disableAutoReturnValueGeneration();
}
优势:
- 除了模拟方法之外,您的所有模拟都不会调用任何内容。无需将
->expects(self::never())->method(self::anything())
绑定到所有这些 - 您仍然可以设置新的模拟。
->expects(self::never())->method(self::anything())
之后你不能
适用于PhpUnit v7.5.4(可能还有更高版本)。
您还可以模拟方法和数据提供程序,并确保它永远不会被调用。 不做任何断言,因为它没有被调用,这意味着它已经通过了测试。
<?php
/**
* @dataProvider dataProvider
*/
public function checkSomethingIsDisabled( $message, $config, $expected)
{
$debugMock = $this->getMockBuilder('APP_Class_Name')
->disableOriginalConstructor()
->setMethods(array('_helper'))
->getMock();
$debugMock = $this->getPublicClass($debugMock);
$debugMock->_config = $config;
$viewContent = new stdClass;
$debugMock->_functionToTest($viewContent);
}
public function dataProvider()
{
return [
'dataset'=>
[
'message' => 'Debug Disabled',
'config' => (object) array(
'values' => (object) array(
'valueThatWhenFalseDoesntExecuteFunc'=> false
)
),
// in a probably needed complimentary "imaginary" test we probably
// will have the valueThatWhenFalseDoesntExecuteFunc set to true and on
// expected more information to handle and test.
'expected' => null
]
];
}