31

I've got a mock object in a test. The real object, PageRepository, implements a magic method using __call(), so if you call $pageRepository->findOneByXXXX($value_of_field_XXXX), it will search the database for records matching that parameter.

Is there a way to mock that method?

The real method call would look something like this:

$homepage = $pageRepository->findOneBySlug('homepage');

The test would look like this:

$mockPageRepository->expects($this->any())
    ->method('findOneBySlug')
    ->will($this->returnValue(new Page()));

But it doesn't work -- PHPUnit doesn't spot the method call. The only way to get it to see the method is to define the method explicitly in PageRepository.

j0k
  • 21,914
  • 28
  • 75
  • 84
Jeremy Warne
  • 3,277
  • 1
  • 27
  • 27

2 Answers2

45

PHPUnit's getMock() takes a second argument, an array with the names of methods to be mocked. If you include a method name in this array, the mock object will contain a method with that name, which expects() and friends will work on.

This applies even for methods that are not defined in the "real" class, so something like the following should do the trick:

$mockPageRepository = $this->getMock('PageRepository', array('findOneBySlug'));

Keep in mind that you'll have to explicitly include any other methods that also need to be mocked, since only the methods named in the array are defined for the mock object.

John Flatness
  • 29,079
  • 5
  • 71
  • 76
  • 5
    Note that, if you need to do complex things via a mock builder (e.g. disable the original constructor) then you have to call `setMethods()` explicitly e.g. `$this->getMockBuilder('ClassName')->setMethods(['findById'])->getMock();` because `getMock()` on the *builder* doesn't take any arguments. – J-P Jul 04 '16 at 12:55
2

I found better way to do this. Still not perfect, but you don't have to specify all mocking class methods by hand, only magic methods:

    $methods = get_class_methods(PageRepository::class);
    $methods[] = 'findOneBySlug';
    $pageRepositoryMock = $this->getMockBuilder(PageRepository::class)
        ->disableOriginalConstructor()
        ->disableOriginalClone()
        ->disableArgumentCloning()
        ->disallowMockingUnknownTypes()
        ->setMethods($methods)
        ->getMock();
Serhii Smirnov
  • 1,153
  • 1
  • 13
  • 21