PHPUnit how to mocker / simulate an object and methods

When you start using PHPunit, you often find yourself faced with 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 the setMethods

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

This product is a mocked object whose methods

  • returns true value
  • are not replaceable

If you pass a array containing method names

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

The methods cited

  • always return null by default
  • are easily replaceable

As for the others

  • returns true value
  • are not replaceable

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

If you find yourself facing a builder who prevents it from being built without knowing some values, it is possible to use the disable optionOriginalConstructor()

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

How to simulate a method

Publicités

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

 
$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 re-unetoune the “myName” thong all the time, but the test will fail if called more than once, while the foobar method call is unlimited and returns the “foo!” thong.

Publicités

Leave a Reply