PHPUnit : Assert a parameter when pass it to mock object

后端 未结 2 659
梦如初夏
梦如初夏 2021-02-18 20:54

For the code below,

$mockObject->expects($this->at(0))
           ->method(\'search\')
           ->with($searchConfig)
           ->will($this-&g         


        
相关标签:
2条回答
  • 2021-02-18 21:32

    You can use Mockery for it

    Say I have a code

    $productValidator = app(ProductValidator:class)->setProduct($productIn);
    

    That would be the test code

    use Mockery;
    
    ...
    
        $productValidator            
            ->shouldReceive('setProduct')->once()
            ->with(Mockery::type(Product::class))
            ->with(Mockery::on(function($productIn) use ($productId) {
                    return $productIn->id === $productId;
                }))
            ->andReturn($productValidator);
    

    Tested on phpunit "version": "8.5.8"

    0 讨论(0)
  • 2021-02-18 21:34

    You can use ->with($this->callback()) and pass in a closure to perform more complex assertions on the argument.

    From the PHPUnit Docs

    The callback() constraint can be used for more complex argument verification. This constraint takes a PHP callback as its only argument. The PHP callback will receive the argument to be verified as its only argument and should return TRUE if the argument passes verification and FALSE otherwise.

    Example 10.13: More complex argument verification

    getMock('Observer', array('reportError'));

        $observer->expects($this->once())
                 ->method('reportError')
                 ->with($this->greaterThan(0),
                        $this->stringContains('Something'),
                        $this->callback(function($subject){
                          return is_callable(array($subject, 'getName')) &&
                                 $subject->getName() == 'My subject';
                        }));
    
        $subject = new Subject('My subject');
        $subject->attach($observer);
    
        // The doSomethingBad() method should report an error to the observer
        // via the reportError() method
        $subject->doSomethingBad();
    } } ?>
    

    So your test would become:

    $mockObject->expects($this->at(0))
    ->method('search')
    ->with($this->callback(
        function ($config){
            if(!isset($config['shouldnothere']) && $config['object']->isValidValue()) {
                return true;
            }
            return false;
        })
    ->will($this->returnValue([]));
    
    0 讨论(0)
提交回复
热议问题