DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

PHPUnit vs. Phake cheatsheet

Giorgio Sironi user avatar by
Giorgio Sironi
·
Apr. 17, 13 · Interview
Like (0)
Save
Tweet
Share
11.23K Views

Join the DZone community and get the full member experience.

Join For Free

Benjamin Eberlei introduced me to Phake with his recent article: it is a Composer-ready PHP library that integrates easily with PHPUnit and provides an independent Test Doubles framework, capable of producing Stubs, Mocks, and Spies. The syntax and object model reminds me of Mockito, the Java Test Double framework from the authors of Growing Object-Oriented Software.

I like tools that do one thing and do it well, and after experimenting with Phake I'm using it on all new code. I am preparing this cheatsheet for my colleagues at Onebip so that they can start using Phake immediately instead of digging through documentation.

Stubs

Stubs are defined as Test Doubles that returned canned values when called, but do not perform assertions and checks of their own. Here is an example with PHPUnit:

$stub = $this->getMock('Namespace\CollaboratorClass');
$stub->expects($this->any())
  ->method('doSomething')
  ->with('param')
  ->will($this->returnValue('returned'));

With Phake, the same becomes:

$stub = Phake::mock('Namespace\CollaboratorClass');
Phake::when($stub)->doSomething('param')->thenReturn('returned');

Stubbing of multiple calls on the same method requires a custom callback in PHPUnit:

$stub = $this->getMock('Namespace\CollaboratorClass');
$stub->expects($this->any())
  ->method('doSomething')
  ->will($this->returnCallback(function($param) {
  $toReturn = array(
  'param1' => 'returned1',
  'param2' => 'returned2',
  }));

With Phake, the fluent interface allows to specify multiple return values:

$stub = Phake::mock('Namespace\CollaboratorClass');
Phake::when($stub)->doSomething('param1')->thenReturn('returned1')
Phake::when($stub)->doSomething('param2')->thenReturn('returned2');

Stubs can also throw exceptions, to simulate a fault in a collaborator at a lower level:

$stub = $this->getMock('Namespace\CollaboratorClass');
$stub->expects($this->any())
  ->method('doSomething')
  ->will($this->throwException(new InvalidArgumentException()));

With Phake:

$stub = Phake::mock('Namespace\CollaboratorClass');
Phake::when($stub)->doSomething('param1')->thenThrow(new InvalidArgumentException());

Mocks

Mocks in PHPUnit requires a specification to be provided before calls to the production code:

$mock = $this->getMock('Namespace\CollaboratorClass');
$mock->expects($this->once())
  ->method('doSomething')
  ->with('param');
// act phase

Mocks in Phake can be specified after the interaction:

$mock = Phake::mock('Namespace\CollaboratorClass');
// act phase
Phake::verify($mock)->doSomething('param');

The benefit of separate verification phases is not only what Benjamin notes: a consistent model of state- and behavior-based testing, where verifications substitute your assertions. Verifying in the test means that exceptions come up and don't have to traverse your code to be seen: at the functional and acceptance level you're avoiding the framework's exceptions to be caught in your catch() clauses.

No interactions with a mock can be verified too:

$mock = $this->getMock('Namespace\CollaboratorClass');
$mock->expects($this->never())
  ->method('doSomething');
// act phase

With Phake:

$mock = Phake::mock('Namespace\CollaboratorClass');
// act phase
Phake::verifyNoInteractions($mock);

And multiple interactions are the last interesting case:

$mock = $this->getMock('Namespace\CollaboratorClass');
$mock->expects($this->at(0))
  ->method('doSomething')
  ->with('param1');
$mock->expects($this->at(1))
  ->method('doSomething')
  ->with('param2');
// act phase

With Phake:

$mock = Phake::mock('Namespace\CollaboratorClass');
// act phase
Phake::verify($mock)->doSomething('param1')
Phake::verify($mock)->doSomething('param2');

Phake supports natively PHPUnit matchers, so you don't have to change them while transforming your expectations into verifications:

$mock = $this->getMock('Namespace\CollaboratorClass');
$mock->expects($this->once())
  ->method('doSomething')
  ->with($this->isInstanceOf('Iterator');
// act phase

With Phake:

$mock = Phake::mock('Namespace\CollaboratorClass');
// act phase
Phake::verify($mock)->doSomething($this->isInstanceOf('Iterator'));

Spies

When expectations are complex and you're not ready to create a Constraint object, Spies provide the capturing of the incoming input to a mock and let you work on this variable to assert what you want, conceptually placing your assertions in the mock.

$mock = $this->getMock('Namespace\CollaboratorClass');
$self = $this;
$mock->expects($this->once())
  ->method('doSomething')
  ->will($this->returnCallback(function($param) use ($self) {
  $self->param = $param;
  }));
// act phase
$self->assertEquals('42', $self->param->answer());

With Phake, you can capture the output too, but after the act phase, consistently with other verifications:

$mock = Phake::mock('Namespace\CollaboratorClass');
// act phase
Phake::verify($mock)->doSomething(Phake::capture($param));
$this->assertEquals('42', $param->answer());

Spies are not to be used frequently - when these verifications are repeated between tests you should extract a Constraint object.

Conclusions

I've pretty much covered all the expectations that I would write every day with PHPUnit or Phake. Phake is a powerful tool that focuses on letting you write and read expectations easily and at the correct phase of your tests; however, don't be blinded by the tool and always simplify the interfaces you are going to introduce Test Doubles for, in the spirit of the Interface Segregation Principle. Also write these protocols and expectations from the point of view of the client class, again in the spirit of another principle, the Dependency Inversion one that leads to the outside-in TDD style proposed by GOOS.

PHPUnit

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Custom Validators in Quarkus
  • Building the Next-Generation Data Lakehouse: 10X Performance
  • Front-End Troubleshooting Using OpenTelemetry
  • Important Data Structures and Algorithms for Data Engineers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: