Mock in PHPUnit - multiple configuration of the same method with different arguments

前端 未结 7 755
死守一世寂寞
死守一世寂寞 2020-11-29 22:26

Is it possible to configure PHPUnit mock in this way?

$context = $this->getMockBuilder(\'Context\')
   ->getMock();

$context->expects($this->any         


        
7条回答
  •  孤街浪徒
    2020-11-29 22:46

    Here are also some solutions with the doublit library :

    Solution 1 : using Stubs::returnValueMap

    /* Get a dummy double instance  */
    $double = Doublit::dummy_instance(Context::class);
    
    /* Test the "offsetGet" method */
    $double::_method('offsetGet')
        // Test that the first argument is equal to "Matcher" or "Logger"
        ->args([Constraints::logicalOr('Matcher', 'Logger')])
        // Return "new Matcher()" when first argument is "Matcher"
        // Return "new Logger()" when first argument is "Logger"
        ->stub(Stubs::returnValueMap([['Matcher'], ['Logger']], [new Matcher(), new Logger()]));
    

    Solution 2 : using a callback

    /* Get a dummy double instance  */
    $double = Doublit::dummy_instance(Context::class);
    
    /* Test the "offsetGet" method */
    $double::_method('offsetGet')
        // Test that the first argument is equal to "Matcher" or "Logger"
        ->args([Constraints::logicalOr('Matcher', 'Logger')])
        // Return "new Matcher()" when first argument $arg is "Matcher"
        // Return "new Logger()" when first argument $arg is "Logger"
        ->stub(function($arg){
            if($arg == 'Matcher'){
                return new Matcher();
            } else if($arg == 'Logger'){
                return new Logger();
            }
        });
    

提交回复
热议问题