How to proactively mock a class that is instantiated by another class

I suspect that the “best” answer to my question is to use dependency injection and completely eliminate this problem. Unfortunately, I do not have such an option ...

I need to write a test for a class that instantiates a third-party library. I want to trick / stub a library class so that it doesn't call API calls in real time.

I use phpunit in the CakePHP v3.x framework. I can mock the library and create responses to the stub, but this does not prevent the "real" class from creating an instance of code outside of my test. I thought I was trying to make fun of the class upstream of the instance, but there are a lot of them, which would make the test incredibly cumbersome to write / support.

Is there a way to somehow "drown" the class instance? Similarly, how can we say that the php module expects an API call and sets the returned data?

+4
source share
2 answers

Using PHPUnit, you can get a mock API class. You can then specify how it will interact with which methods and arguments are used.

Here is an example from phpunit.de (chapter 9):

public function testObserversAreUpdated()
{
    // Create a mock for the Observer class,
    // only mock the update() method.
    $observer = $this->getMockBuilder('Observer')
                     ->setMethods(array('update'))
                     ->getMock();

    // Set up the expectation for the update() method
    // to be called only once and with the string 'something'
    // as its parameter.
    $observer->expects($this->once())
             ->method('update')
             ->with($this->equalTo('something'));

    // Create a Subject object and attach the mocked
    // Observer object to it.
    $subject = new Subject('My subject');
    $subject->attach($observer);

    // Call the doSomething() method on the $subject object
    // which we expect to call the mocked Observer object's
    // update() method with the string 'something'.
    $subject->doSomething();
}

If the API returns something, you can add will () to the second statement as follows:

   ->will($this->returnValue(TRUE));
0
source

, , "" - , . , , :

  • mock API
  • /
0

Source: https://habr.com/ru/post/1627210/


All Articles