很难从粘贴的代码片段中准确地判断出您要在测试文件中执行的操作,但您可以模拟闭包及其参数。这是一个快速/肮脏/未经测试的示例,可以最好地猜测您要完成的工作:
class Transformer {
protected transformerFactory;
public function __construct($factory) {
$this->transformerFactory = $factor;
}
public function doSomething(Discount $discount, ProductInterface $product) {
return $this->transformerFactory->createProductTransformer($product, function($product) use ($discount) {
$product->setDiscount($discount);
});
}
}
class TransformerTest {
protected function makeTransformerWithFakeFactory()
{
$fakeFactory = \Mockery::mock('TransformerFactory');
$transformer = new Transformer($fakeFactory);
return array($tranformer, $fakeFactory);
}
protected function fakeDiscount()
{
return \Mockery::mock('Discount');
}
protected function fakeProduct()
{
return \Mocker::mock('ProductInterface');
}
// first let's test to make sure that the factory's correct method is called with correct parameters
function test_doSomething_WhenPassedProduct_CallsCreateProductTransformerOnFactoryWithProductAndClosure()
{
list($transformer, $mockFactory) = $this->makeTransformerWithFakeFactory();
$fakeDiscount = $this->fakeDiscount();
$fakeProduct = $this->fakeProduct();
$mockFactory->shouldReceive('createProductTransformer')->once()->with($fakeProduct, \Mockery::type('Closure'));
$transfomer->doSomething($fakeDiscount, $fakeProduct);
}
// now, let's test to make sure that the $discount within the closure is called with the right method and params
function test_doSomething_createProductTransformerCalledWithProductAndClosure_CallsSetDiscountOnProductWithDiscount()
{
list($transformer, $stubFactory) = $this->makeTransfomerWithFakeFactory();
$fakeDiscount = $this->fakeDiscount();
$mockProduct = $this->fakeProduct();
$stubFactory->shouldReceive('createProductTransfomer')->passthru();
$mockProduct->shouldReceive('setDiscount')->once()->with($fakeDiscount);
$transfomer->doSomething($fakeDiscount, $mockProduct);
}
// now lets make sure that doSomething returns what the call to factory's createProductTransformer method returns
function test_doSomething_createProductTransformerCalledWithProductAndClosureReturnsValue_ReturnsSameValue()
{
list($transformer, $stubFactory) = $this->makeTransfomerWithFakeFactory();
$fakeDiscount = $this->fakeDiscount();
$fakeProduct = $this->fakeProduct();
$stubFactory->shouldReceive('createProductTransfomer')->andReturn('transformed result');
$result = $transfomer->doSomething($fakeDiscount, $fakeProduct);
$this->assertEquals('transformed result', $result);
}
}