phpunit testing method that calls other class methods which need mock

前端 未结 2 1279
终归单人心
终归单人心 2021-02-03 23:37

I\'m trying to create a pretty standard unit test where I call a method and assert it\'s response, however the method I\'m testing calls another method inside the same class whi

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 23:50

    You can specify which methods to mock (partial mock) with setMethods():

     // Let's do a `partial mock` of the object. By passing in an array of methods to `setMethods`
     // we are telling PHPUnit to only mock the methods we specify, in this case `handleValue()`.
    
    $csc = $this->getMockBuilder('Lightmaker\CloudSearchBundle\Controller\CloudSearchController')
                 ->setConstructorArgs($constructor)
                 ->setMethods(array('handleValue'))
                 ->getMock();
    
     // Tell the `handleValue` method to return 'bla'
     $csc->expects($this->any())
         ->method('handleValue')
         ->with('bla');
    

    Any other methods in the class not specified in the array you give setMethods() will be executed as is. If you do not use setMethods all methods will return NULL unless you specifically set them.

提交回复
热议问题