How can I get PHPUnit MockObjects to return different values based on a parameter?

前端 未结 11 1586
忘掉有多难
忘掉有多难 2020-12-04 05:43

I\'ve got a PHPUnit mock object that returns \'return value\' no matter what its arguments:

// From inside a test...
$mock = $this->getMock(\         


        
相关标签:
11条回答
  • 2020-12-04 06:25

    I had a similar problem which I couldn't work out as well (there's surprisingly little information about for PHPUnit). In my case, I just made each test separate test - known input and known output. I realised that I didn't need to make a jack-of-all-trades mock object, I only needed a specific one for a specific test, and thus I separated the tests out and can test individual aspects of my code as a separate unit. I'm not sure if this might be applicable to you or not, but that's down to what you need to test.

    0 讨论(0)
  • 2020-12-04 06:25

    Try :

    ->with($this->equalTo('one'),$this->equalTo('two))->will($this->returnValue('return value'));
    
    0 讨论(0)
  • 2020-12-04 06:28

    Do you mean something like this?

    public function TestSomeCondition($condition){
      $mockObj = $this->getMockObject();
      $mockObj->setReturnValue('yourMethod',$condition);
    }
    
    0 讨论(0)
  • 2020-12-04 06:30

    You also can return the argument as follows:

    $stub = $this->getMock(
      'SomeClass', array('doSomething')
    );
    
    $stub->expects($this->any())
         ->method('doSomething')
         ->will($this->returnArgument(0));
    

    As you can see in the Mocking documentation, the method returnValue($index) allows to return the given argument.

    0 讨论(0)
  • 2020-12-04 06:36

    You would probably want to do a callback in a OOP fashion:

    <?php
    class StubTest extends PHPUnit_Framework_TestCase
    {
        public function testReturnAction()
        {
            $object = $this->getMock('class_name', array('method_to_mock'));
            $object->expects($this->any())
                ->method('method_to_mock')
                ->will($this->returnCallback(array($this, 'returnCallback'));
    
            $object->returnAction('param1');
            // assert what param1 should return here
    
            $object->returnAction('param2');
            // assert what param2 should return here
        }
    
        public function returnCallback()
        {
            $args = func_get_args();
    
            // process $args[0] here and return the data you want to mock
            return 'The parameter was ' . $args[0];
        }
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题