0

I'm testing that my factory will return object

public function createManager(string $className): object{
  return $this->managerFactory->createManager($className);
}

My test:

  /**
   * @test
   */
  public function createManagerReturnsObject() {
    $util = new Util();
    
    // mocking class
    $util->managerFactory = $this
                        ->getMockBuilder( ManagerFactory::class)
                        ->setMethods(['createManager'])
                       //->disableArgumentCloning()
                        ->getMock();

    // expectation
    $expect = (object)array('token' => 'Foo');

    $this->object = $expect;
    
    // mocking method
    $util->managerFactory->method('createManager')
                         ->will(
                          $this->returnCallback(function($passed_value){
                            $this->object->token = $passed_value;
                            return $this->object;
                          }));

    // testing
    $manager = $util->createManager('Bar');

    //var_dump($expect);
    
    // assertion
    $this->assertEquals($expect, $manager);
  }

This test supposed to fail. But my mocking method callback changed $expect to Bar.

The question is: how variable $this->object changed $expect? Any better solutions to test this method?

Mindaugas
  • 23
  • 1
  • 3
  • 1
    This is most likely due to https://stackoverflow.com/questions/16893949/php-object-assignment-vs-cloning, `$this->object` is a reference to `$expect` and not a copy. – Nigel Ren Apr 11 '21 at 07:11
  • Thank you for this link, you a right. I was treating objects as strings, I replaced line ```$this->object = clone $expected;``` and ```$expected``` didn't changed after mocking method executed. – Mindaugas Apr 11 '21 at 07:51

0 Answers0