Creating a mock in phpunit without mocking any methods?

前端 未结 5 1744
情深已故
情深已故 2020-12-29 01:53

When I\'m unit-testing my php code with PHPUnit, I\'m trying to figure out the right way to mock an object without mocking any of its methods.

The problem is that if

相关标签:
5条回答
  • 2020-12-29 02:15

    This worked for me:

    $this->getMock($class, array(), array(), '', false);
    
    0 讨论(0)
  • 2020-12-29 02:20

    In case, any method, e.g. that is called through the entityManager, can be used you might be able to use this:

    $this->entityManager
            ->expects($this->any())
            ->method($this->anything())
            ->willReturn($repository);
    
    0 讨论(0)
  • 2020-12-29 02:33

    Another hacky, but succinct solution is simply to list the magic constructor as one of the mocked methods:

    $mock = $this->getMock('MyClass', array('__construct'));
    
    0 讨论(0)
  • 2020-12-29 02:37

    You can pass null to setMethods() to avoid mocking any methods. Passing an empty array will mock all methods. The latter is the default value for the methods as you've found.

    That being said, I would say the need to do this might point out a flaw in the design of this class. Should this method be made static or moved to another class? If the method doesn't require a completely-constructed instance, it's a sign to me that it might be a utility method that could be made static.

    0 讨论(0)
  • 2020-12-29 02:37

    Or you can just use getMock() directly.

    $mock = $this->getMock('MyClass', null, array(), null, false);

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