phpunit testing method that calls other class methods which need mock

前端 未结 2 1304
终归单人心
终归单人心 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.

提交回复
热议问题