Home > Project > pt_mock: Mock objects when testing in php

pt_mock: Mock objects when testing in php

When I started with TDD in PHP, some years ago, I used the mock feature of PHPUnit but it disgust me a lot. At that time I worked at Domestika with Mathias Biilmann and Rodrigo Alvarez. All together we decided to create our mock class to work in a more simple way.

When I left Domestika I wrote, from the begining, my own version of that mock object with a similar behaviour of the original mock object but adding some new features.

Now I have finally published the code in github as a public open source project.

[ https://github.com/gramos74/pt_mock ]

Some examples of how to use it:

We have a method class that receives a object as parameter. Inside this method
we will call the object method ‘method_mock’ with parameter ‘a’
and we expect that it returns ‘b’.

    class class_a {

        function my_method($class_b) {
            return $class_b->method_mock(‘a’);


    $class_b = new pt_mock(‘Class B’);

    $class_a = new class_a();
    echo $class_a->my_method($class_b); // —-> ‘b’

To check that all expectations have been accomplished :

    $class_b->verify(); // for a instance of pt_mock
    pt_mock::verify_all(); // for all mocks instantiated

If you want to test that the method is called two times:


Sometimes you don’t want to test if a method is called, you only want that if a
method is called the mock object returns a value based on parameters.


    echo $class_b->method_mock(‘a’) —> ‘b’
    echo $class_b->method_mock(‘a’) —> ‘b’
    echo $class_b->method_mock(‘a’) —> ‘b’
    echo $class_b->method_mock(‘a’) —> ‘b’

And sometimes you want to raise a exception instead of to return data.

    $class_b->stubs(‘method_mock’)->with(‘a’)->raises(new Exception());

    echo $class_b->method_mock(‘a’) —> raises a exception

I hope that you find it useful.

Categories: Project Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: