Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of using Spies
<?php
class GreetingGenerator {
public function get_greeting( $name ) {
// Assumes determine_greeting is defined in another file
return determine_greeting( $name );
}
}
class Greeter {
public function __construct( $greeting_generator ) {
$this->generator = $greeting_generator;
}
public function greet( $name ) {
return $this->generator->get_greeting( $name ) . ' ' . $name;
}
}
class GreeterTest extends PHPUnit_Framework_TestCase {
public function tearDown() {
\Spies\finish_spying();
}
public function test_greeter_greet_returns_result_of_get_greeting() {
$mock_generator = \Spies\mock_object_of( 'GreetingGenerator' );
$mock_generator->add_method( 'get_greeting' )->when_called->will_return( 'yo' );
$greeter = new Greeter( $mock_generator );
$this->assertEquals( 'yo joe', $greeter->greet( 'joe' ) );
}
public function test_greeter_passes_name_to_get_greeting() {
$mock_generator = \Spies\mock_object_of( 'GreetingGenerator' );
$spy = $mock_generator->spy_on_method( 'get_greeting' );
$greeter = new Greeter( $mock_generator );
$greeter->greet( 'joe' );
// Using an Expectation:
\Spies\expect_spy( $spy )->to_have_been_called->with( 'joe' );
// Or, without using an Expectation:
$this->assertTrue( $spy->was_called_with( 'joe' ) );
}
public function test_greeter_uses_return_value_of_determine_greeting() {
\Spies\stub_function( 'determine_greeting' )->when_called->will_return( 'my good friend' );
$greeter = new Greeter( new GreetingGenerator() );
$this->assertEquals( 'my good friend joe', $greeter->greet( 'joe' ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment