【发布时间】:2017-03-01 01:32:01
【问题描述】:
我需要测试以下功能:
[...]
public function createService(ServiceLocatorInterface $serviceManager)
{
$firstService = $serviceManager->get('FirstServiceKey');
$secondService = $serviceManager->get('SecondServiceKey');
return new SnazzyService($firstService, $secondService);
}
[...]
我知道,我可能会这样测试:
class MyTest extends \PHPUnit_Framework_TestCase
{
public function testReturnValue()
{
$firstServiceMock = $this->createMock(FirstServiceInterface::class);
$secondServiceMock = $this->createMock(SecondServiceInterface::class);
$serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);
$serviceManagerMock->expects($this->at(0))
->method('get')
->with('FirstServiceKey')
->will($this->returnValue($firstService));
$serviceManagerMock->expects($this->at(1))
->method('get')
->with('SecondServiceKey')
->will($this->returnValue($secondServiceMock));
$serviceFactory = new ServiceFactory($serviceManagerMock);
$result = $serviceFactory->createService();
}
[...]
或
[...]
public function testReturnValue()
{
$firstServiceMock = $this->createMock(FirstServiceInterface::class);
$secondServiceMock = $this->createMock(SecondServiceInterface::class);
$serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);
$serviceManagerMock->expects($this->any())
->method('get')
->withConsecutive(
['FirstServiceKey'],
['SecondServiceKey'],
)
->willReturnOnConsecutiveCalls(
$this->returnValue($firstService),
$this->returnValue($secondServiceMock)
);
$serviceFactory = new ServiceFactory($serviceManagerMock);
$result = $serviceFactory->createService();
}
[...]
两者都可以正常工作,但如果我在 createService 函数中交换 ->get(xxx) 行,两个测试都会失败。 那么,我该如何更改不需要特定序列的测试用例参数'FirstServiceKey','SecondServiceKey,......
【问题讨论】:
-
你试过用
$this->any()代替$this->at(0)吗? -
是的,那是我的第一次尝试。导致错误:调用零次或多次时,方法名称的期望失败等于
调用参数 0 -
是的,最初我没有仔细阅读您的问题。希望我的回答能满足你的需要
标签: unit-testing zend-framework2 phpunit