Code sur écran d'ordinateur

PHPUnit how to mocker / simulate an object and methods

When you start using PHPUnit, you often find yourself facing the need to simulate a method or object. Fortunately PHPUnit has some methods that can be very useful.

How to simulate an object

The easiest way to create a mocked object

 
$product - $this--getMockBuilder ('Product')
                -getMock(;

or

 
$product - $this--getMockBuilder ('Product')
                -setMethods (array))
                -getMock(;

This product is a mocked object whose methods

  • are all present
  • always return null by default
  • are easily replaceable

If on the other hand we pass null in setMethods

 
$product - $this--getMockBuilder ('Product')
                -setMethods (null)
                -getMock(;

This product is a mocked object whose methods

  • return the real value
  • are not replaceable

If you pass an array containing method names

 
$product - $this--getMockBuilder ('Product')
                -setMethods (array ('getName', 'foobar')
                -getMock(;

The methods listed

  • always return null by default
  • are easily replaceable

As for the others

  • return the real value
  • are not replaceable

Basically this means that all methods of the Product object will return their real values except getName and foobar which will return null.

If you find yourself facing a constructor that prevents it from being built without knowing some values, it is possible to use the disableOriginalConstructor() option

 
$product - $this--getMockBuilder ('Product')
                OriginalConstructor()
                -setMethods (array ('getName', 'foobar')
                -getMock(;

How to simulate a method

Once the object is mocked, it is also possible to replace the return value of a method. To do this, just use the ->expects method

 
$product - $this--getMockBuilder ('Product')
                -setMethods (array ('getName', 'foobar')
                -getMock(;

$product-expects ($this--ounce))
        --method ('getName')
        will ($this--returnValue ('myName');

$product-expects ($this-any())
        --method ('foobar')
        --will($this--returnValue ('foo!';

In this example, the getName method will always return the string “myName”, but the test will fail if it is called more than once, while the foobar method call is unlimited and returns the string “foo!”.

Leave a comment