Generate mocks and stubs with PHPUnit

Very interesting presentation of Juan Treminio about unit tests and PHPUnit: PDF. He explain how to generate mocks and stubs using the MockBuilder:

  • Generate a basic mock, without call setMethods() method:
    * All methods in mocked object are stubs
    * Return null
    * Methods easily overridable

    $payment = $this->getMockBuilder('AuthorizeNetAIM')
                    ->getMock();
  • Pass an empty array
    * Same as if not calling setMethods()
    * All methods in mocked object are stubs
    * Return null
    * Methods easily overridable

    $payment = $this->getMockBuilder('AuthorizeNetAIM')
                    ->setMethods(array())
                    ->getMock();
  • Pass null
    * All methods in mocked object are mocks
    * Run actual code in method
    * Not overridable

    $payment = $this->getMockBuilder('AuthorizeNetAIM')
                    ->setMethods(null)
                    ->getMock();
  • Pass an array with method names
    –Methods identified are stubs
    • Return null
    • Easily overridable
    –Methods *not* identified are mocks
    • Actual code is ran
    • Unable to override

    $payment = $this->getMockBuilder('Payment')
                    ->setMethods(
                        array('authorizeAndCapture',)
                    )
                    ->getMock();

Source – Juan Treminio presentation
Source – Juan Treminio blog

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>