phpunit testing method that calls other class methods which need mock

前端 未结 2 1280
终归单人心
终归单人心 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:47

    You can mock the class that you are testing and specify the method that you want to mock.

    $mock = $this->getMockBuilder('MyClass')
        ->setMethods(array('handleValue'))
        ->getMock();
    
    $mock->expects($this->once())
        ->method('handleValue')
        ->will($this->returnValue(23)) //Whatever value you want to return
    

    However, IMO this is not the best idea for your tests. Testing like this will make refactoring much more difficult. You are specifying the implementation of the class rather than the behavior that the class is supposed to have. If handleValue is doing a lot of complicated work that makes testing difficult, consider moving the logic into a separate class and injecting that into your class. Then you can create a mock of that class and pass it in to testMethod. Doing so will give you the added advantage of making MyClass more extensible if handleValue needs to adapt its behavior.

    http://www.oodesign.com/strategy-pattern.html

    As a general rule, you should not mock the system that you are testing.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题