PHP Mocking Framework

Related tags

Testing phake
Overview

Phake

Documentation Status Build Status Latest Stable Version Total Downloads Latest Unstable Version License

Phake is a framework for PHP that aims to provide mock objects, test doubles and method stubs.

Phake was inspired by a lack of flexibility and ease of use in the current mocking frameworks combined with a recent experience with Mockito for Java.

A key conceptual difference in mocking between Phake and most of php mocking frameworks (ie: mock functionality in PHPUnit, PHPMock, and mock functionality in SimpleTest) is that Phake (like Mockito) employs a verification strategy to ensure that calls get made. That is to say, you call your code as normal and then after you have finished the code being tested you can verify whether or not expected methods were called. This is very different from the aforementioned products for php which use an expectation strategy where you lay out your expectations prior to any calls being made.

Installation - Composer

Phake can be installed using Composer.

  1. Add Phake as a dependency.

You'll usually want this as a development dependency, so the example shows it in the require-dev section.

"require-dev": {
	"phake/phake": "4.*"
}
  1. Run Composer: php composer.phar install --dev or php composer.phar update phake/phake

Installation - Source

You can also of course install it from source by downloading it from our github repository: https://github.com/mlively/Phake

Links

There are a few links that have information on how you can utilize Phake.

If you have an article or tutorial that you would like to share, feel free to open an issue on github and I will add it to this list

Comments
  • Temporary fix for #301

    Temporary fix for #301

    Like I said in #301 this is only a temporary fix to avoid the deprecation error. The real work to do to prepare PHP 9.0 correctly is to infer the good return type, which is not OK with interfaces currently.

    Defect 
    opened by niconoe- 9
  • Legacy Code - Returning via reference

    Legacy Code - Returning via reference

    We have a legacy class with a method, which returns value via reference:

    <?
    public function &foo() {}
    

    When we Phake::mock() it, we recieve: Strict Standards: Declaration of $mockedMethod should be compatible with that of $realMethod

    opened by dagguh 8
  • Add support for PHP8

    Add support for PHP8

    Hi,

    This PR add support to PHP8 (and drop support for PHP<7.1). I'm not familiar at all with the Phake internal code so it's very much appreciated if you could have a look at this PR to make sure I did nothing wrong.

    The quick steps that I did were :

    • Change the tests to work on both phpunit 7.0 and 8.0
    • Update doctrine/common to use ^3.0
    • Add new Phake_ClassGenerator_MockClass::implementType method that support both named and union Types

    I did test on my local on php7.1 php7.3 php7.4 and 8.0 and everything works fine. I did not had the time to add more tests but feel free to add some or contribute to this PR :-)

    Thanks

    opened by adoy 7
  • ReflectionType::__toString() is deprecated in PHP 7.4

    ReflectionType::__toString() is deprecated in PHP 7.4

    PHPUnit throws deprecation errors when Phake uses this method in PHP 7.4

    ErrorException: Function ReflectionType::__toString() is deprecated

    This patch replaces the instances of (string)$returnType with $returnType->getName(); allowing Phake to work on PHP 7.4 without deprecation warnings/errors.

    Resolves issue #279

    opened by slt 7
  • Prevent constructor override when constructor is final

    Prevent constructor override when constructor is final

    During my test, I wanted to mock a class with a final constructor like this one https://github.com/doctrine/annotations/blob/master/lib/Doctrine/Common/Annotations/Annotation.php which has a final constructor.

    I have added a test for this case.

    What are your thoughts about this issue?

    Regards

    opened by nicolasThal 7
  • Allow direct calling of protected methods for mocks

    Allow direct calling of protected methods for mocks

    We like to test our protected methods because some of them do contain logic. Now, if that method contain calls to other methods, we also want to verify that the call happened correctly. Verification though as far as I can tell only works with mock objects. We tried using PHPUnit_Extensions_Helper_AccessibleObject but it does not allow making the method public on these mocks. Can we add it, either by default or via a flag, the ability to automatically make a method public? So basically, we needed the ability to do the following (in very simple terms):

    class MyClass {
        ...
        protected function doWork($raw) {
            $data = $this->processRaw($raw);
            return array('result' => $data);
        }
        ...
    }
    
    class MyClassTest {
        public function testDoWork() {
            $mock = Phake::partialMock('MyClass');
            self::assert(array('result' => 'BLAH'), $mock->doWork('blah'));
    
            Phake::verify($mock)->processRaw(...);
        }
    }
    
    Enhancement 
    opened by duclet 7
  • Phake breakes auto completion/inspection feature of modern IDEs

    Phake breakes auto completion/inspection feature of modern IDEs

    Almost every modern IDE supports auto completion through PHPDoc annotations. But with the current Phake API it isn't possible to make use of this feature.

    As example with PHPStorm:

    Every time I write a Phake:when() call I must write a /** @noinspection PhpUndefinedMethodInspection */ to tell the IDE it should disable the inspection for this call. This clutters the source code with unnecessary @noinspection annotations.

    Furthermore it isn't possible to use the auto completion feature.

    <?php
    
    class FooTest extends PHPUnit_Framework_TestCase {
    
        public function testSomeBehaviour() {
    
            /* @var Foo $mock */
            $mock = Phake::mock('Foo');
            when($mock)-> //No auto completion available
        }
    }
    

    So my question is why not using the Mockito syntax for Phake.

    <?php
    
    class FooTest extends PHPUnit_Framework_TestCase {
    
        public function testSomeBehaviour() {
    
            /* @var Foo $mock */
            $mock = Phake::mock('Foo');
            when($mock->doSomething())->thenReturn(1);
        }
    }
    

    Are there technical reasons or what was your decision to break with the Mockito syntax?

    opened by akkie 7
  • Include LICENSE , README and CHANGELOG in package.xml

    Include LICENSE , README and CHANGELOG in package.xml

    I am creating an RPM for Fedora and EPEL and this came up in the review progress: https://bugzilla.redhat.com/show_bug.cgi?id=818318#c3:

    So you can request to add CHANGELOG, LICENSE and README with role="doc" and to add tests folder as role="test" (next step will be to add a %check in the spec to run this test suite), as this files are already there.

    I can include them manually, but it would be nicer if they would be included in the pear package. Sometimes other packages also things like composer.json .

    opened by christofdamian 7
  • Mocking Static Methods documentation seems misleading

    Mocking Static Methods documentation seems misleading

    In this case, because the static:: keyword will cause the called class to be determined at runtime, you will be able to verify and stub calls to StaticFactory::factory().

    Source

    This doesn't seem accurate. Calls to StaticFactory::getInstance() are still bound to that class name and will still invoke the StaticFactory version of factory(). You can create a mock of StaticFactory and stub factory() on that object's class, in which case the use of static:: in getInstance() will resolve to the mock's version of factory(), but only if getInstance() is called using the mock's class name.

    None of this seems like it would be useful unless one of these scenarios applies:

    1. The class containing the static method being stubbed is also the class under test, in which case we're involving either partial mocks or the thenCallParent() answer, which the documentation notes are both intended for legacy code where the section on mocking static methods contains no similar reference to legacy code.
    2. The static method being stubbed is invoked by the code under test where the class off of which that invocation takes place is variable and configurable.

    Would appreciate any feedback you can provide. I'm completely open to the possibility that I'm just lost when it comes to using this feature as intended. :)

    opened by elazar 6
  • Update Packagist with latest tags

    Update Packagist with latest tags

    Packagist only has the dev-master branch available. It would be nice to be able to use the tags you've created.

    If you set up a Packagist post-receive hook in GitHub, it should happen automatically in future.

    opened by ezzatron 6
  • Added docs to package fix issue #64

    Added docs to package fix issue #64

    I were not able to fix #64 without moving everything around. So here is an pull request doing just that. I quite understand if you don't like to do it.

    opened by christofdamian 6
  • WIP - Store mock info outside of the object

    WIP - Store mock info outside of the object

    This is an experimental branch to move all mocking storage (Mock\Info objects) out of the mock object. This will make it possible to mock readonly objects.

    opened by adoy 0
  • Change of behavior when calling parent methods statically

    Change of behavior when calling parent methods statically

    Noticed this while trying to upgrade from 2.1.1 to 3.1.6

    class behaviorChange {
        public static function tryB() {
            return static::b();
        }
        public function b() {
            return "here";
        }
    }
    
    class behaviorChangeTest {
        public function testTryB() {
            $mock = Phake::mock('behaviorChange');
            Phake::whenStatic($mock)->tryB->thenCallParent();
            Phake::whenStatic($mock)->b->thenReturn('there');
           print_r($mock::tryB());
        }
    } 
    

    in 2.1.1 the created Phake class called directly into the parent, which kept the late static binding associated to the mock, resulting in the static::b call correctly being mocked as well (returning 'there')

    however in 3.1.6 the Phake class calles ParentDelegateCallback->__invoke() which calls invokeArgs, which calls reflectionMethod with a null context. This means the late static binding will no longer be the mock, but instead be the SUT. static::b then does not hit the mock (returning 'here')

    I suspect passing the mock as the context would fix it rather than null, but without looking it doesn't seem like an easy thing to do

    opened by theilig 0
  • Serialization of mock issues

    Serialization of mock issues

    I came across a bit of an edge-case in a test which touched the database. I was using a Phake mock as follows:

    $mock = Phake::mock(MyClass::class);
    Phake::when($mock)->myMethod->thenThrow(new MyException);
    

    The issue was that later in the test, I was passing the mock as a constructor argument to the Class Under Test and then trying to serialize the CUT. I was getting the error: You cannot serialize or unserialize PDO instances

    The thing is that MyClass did not have anything to do with the database, and neither did the CUT or any of its dependencies.

    After a lot of debugging I found that the mock object had the instance of the exception stored as a data property a long way down the nested structure, and the exception itself had a trace property which included all of the global context from the test class, including the CakePHP fixture manager, which of course had a PDO instance inside it!

    So this was really unexpected behaviour and after losing a few hours, in the end I could not use Phake to mock this class because of it.

    I'm not sure if there is a solution to this. Perhaps Phake mocks could implement __sleep() in such a way as to exclude expected exceptions?

    opened by garethellis36 0
  • Phaked nullable return type object will return phaked object

    Phaked nullable return type object will return phaked object

    If a class declares a function with a nullable return type

    public function find(int $id): ?Foo
    {
        return $this->repository->find($id);
    }
    

    Then, when mocking this object without specifying behaviour for this method (Phake::when(...) ), Phake will automatically return a Phaked object of this type instead of null

    Enhancement 
    opened by FredM 2
  • Syntax error trying to mock Memcache on PHP 7.1

    Syntax error trying to mock Memcache on PHP 7.1

    Just running:

    <?php
    require_once('vendor/autoload.php');
    Phake::mock('Memcache');
    

    With Memcache installed results in:

    [root@4bc9bbc433aa tests]# php debug.php
    PHP Parse error:  syntax error, unexpected '$', expecting variable (T_VARIABLE) in /var/www/tests/vendor/phake/phake/src/Phake/ClassGenerator/EvalLoader.php(59) : eval()'d code on line 477
    

    Here's the class definition that's trying to eval: classDef.php.txt

    The problem seems to be that it's failing to extract the parameter names for the get method and so the signature is not valid php:

    	public function get($, &$, &$)
    

    This works fine under PHP 5.4 & 5.6, it's only failing for me under PHP 7.1 - using Phake v2.3.2 across all 3.

    opened by neerolyte 3
Releases(v4.3.0)
  • v4.3.0(Dec 19, 2022)

  • v4.2.0(Nov 27, 2021)

    New Features

    #304 - Add support for PHP8.1 new in initializers PHP8.1 introduced new in initializers Phake 4.2 can now create mock of object using this feature.

    #303 - Add support for PHP8.1 intersection types and never return type PHP8.1 introduced intersection types and never return type. Phake 4.2 supports those new types. When a mocked method returning never is called, Phake will by default throw a Phake\Exception\NeverReturnMethodCalledException exception. Calling Phake::when($mock)->thenReturn($x) will have no effect on this method result.

    Changes

    #301 - Add #[\ReturnTypeWillChange] on mocked internal methods on PHP8.1+ All internal mocked method under PHP8.1+ will have #[\ReturnTypeWillChange] attribute to avoid any Deprecation warnings.

    Source code(tar.gz)
    Source code(zip)
  • v3.1.9(May 10, 2021)

  • v4.1.0(Apr 24, 2021)

    Add support for PHP8.0 named parameters
    PHP8.0 introduced Named arguments

    $mock = Phake::mock('PhakeTest_MockedClass');
    Phake::when($mock)->fooWithLotsOfParameters(parm3: 3, parm2: 2, parm1: 1)->thenReturn(42);
    
    $this->assertSame(42, $mock->fooWithLotsOfParameters(1, 2, 3));
    
    Phake::verify($mock)->fooWithLotsOfParameters(parm3: 3, parm2: 2, parm1: 1);
    
    Source code(tar.gz)
    Source code(zip)
  • v4.0.0(Mar 30, 2021)

    • Add support for PHP8 union types
    • Add support for PHP8 annotations (attributes) #[Phake\Mock]
    • Change code to use PSR4 standard instead of PSR0
    • Allow Throwable in thenThrow() and not juste Exception
    Source code(tar.gz)
    Source code(zip)
  • v3.1.8(May 11, 2020)

  • v3.1.7(Dec 6, 2019)

  • v3.1.6(Jun 6, 2019)

  • v3.1.5(May 24, 2019)

  • v3.1.4(May 24, 2019)

  • v3.1.3(Aug 4, 2018)

    Fixed instances of Phake being used in projects where both old and new versions of PHPUnit classes existed. Defaults to use the newer version.

    Source code(tar.gz)
    Source code(zip)
  • v3.1.2(Jul 26, 2018)

  • v3.1.1(Jul 5, 2018)

  • v3.1.0(Jul 5, 2018)

  • v3.0.1(Sep 6, 2017)

  • v3.0.0(Jul 4, 2017)

    This release provides support for php 7.1 functionality as well as support for PHPUnit 6. All support for PHP 5 and PHPUnit 5 are officially removed.

    Fixes

    #235, #236 - PHPUnit 6 compatibility enabled #237 - Fatal error when mocking a final class #239, #248 - thenDoNothing() missing on Phake_Proxies_AnswerCollectionProxy #242, #243, #247 - Allow nullable scalar type support

    Source code(tar.gz)
    Source code(zip)
  • v2.3.2(Mar 20, 2017)

  • v2.3.1(Mar 16, 2017)

    The "get off your butt and merge some PRs" / "Thanks for being patient with me" release

    Fixes:

    • #219 - Fix Phake::resetStatic() post calls (Thanks @shaikhul)
    • #222 - Keep cached version of matcher factory and comparator factory around (Thanks @willemstuursma)
    • #223 - Speed up method implementation. (Thanks @timheilig)
    • #228 - Fix "Mocking Static Methods" documentation example (Thanks @oochelz)
    • #232 - Make matchers work with PHPUnit 6 (Thanks @hansdubois)
    Source code(tar.gz)
    Source code(zip)
  • v2.3.0(Apr 1, 2016)

    New Features

    • #217 Added ability to mock "unsafe classes" - Fixes #214
    • #216 Provided a new answer to return self (Phaks::when($mock)->thenReturnSelf() - Addresses #215
    Source code(tar.gz)
    Source code(zip)
  • v2.2.0(Nov 30, 2015)

    What's New in 2.2.0

    Bugfixes

    #190 - Clean up method that creates mocks This allowed for getting rid of the error suppression operator which appeared to cause crashes in PHP 5.6.10

    Changes

    #205 - Performance improvement (thanks @timheilig)

    #199 - Allow mocking multiple interfaces at once

    #198 - Full support for PHP7 scalar type hints and return types

    #196 - Support for mocking methods with variadic arguments

    Source code(tar.gz)
    Source code(zip)
  • v2.1.1(Sep 27, 2015)

    What's New in 2.1.1

    Bugfixes

    #190 - Clean up method that creates mocks This allowed for getting rid of the error suppression operator which appeared to cause crashes in PHP 5.6.10

    Changes

    Integrated with Code Climate https://codeclimate.com/github/mlively/Phake

    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(May 9, 2015)

    What's New in 2.1.0

    New Features

    #158 - Allow direct calling of protected methods for mocks Allow for calling of private and protected methods on mocks using new Phake::makeVisible() and Phake::makeStaticsVisible() wrappers. This will allow for slightly easier testing of legacy code and abstracts. http://phake.readthedocs.org/en/2.1/mocks.html#calling-private-and-protected-methods-on-mocks

    Changes

    #178 - Renamed thenGetReturnByLambda to thenReturnCallback The thenGetReturnByLambda just didn't quite sound right and was difficult to remember so we changed the name. While the original method will still work, a deprecation error will be emitted by the code when thenGetReturnByLambda is called with a message that you should use thenReturnCallback instead. The great news is that no other project in their right mind would ever use that method name, so a search and replace should be pretty reliable.

    #144 - Improve Phake::verify error message When a method doesn't match you will now be given a more appropriate diff as to why. This should help make life a little easier when debugging failing tests.

    Enhanced integration with Travis-CI We are now testing all the things!

    Integrated with Scrutenizer We are also measuring all the things

    Source code(tar.gz)
    Source code(zip)
  • v2.0.2(Mar 21, 2015)

  • v2.0.1(Mar 4, 2015)

  • v2.0.0-beta2(May 5, 2014)

  • v2.0.0-beta1(Apr 19, 2014)

  • v1.0.5(Apr 16, 2014)

  • v1.0.4(Apr 6, 2014)

Owner
Phake
PHP Mocking Framework
Phake
PHP Mocking Framework

Phake Phake is a framework for PHP that aims to provide mock objects, test doubles and method stubs. Phake was inspired by a lack of flexibility and e

Phake 469 Dec 2, 2022
The most powerful and flexible mocking framework for PHPUnit / Codeception.

AspectMock AspectMock is not an ordinary PHP mocking framework. With the power of Aspect Oriented programming and the awesome Go-AOP library, AspectMo

Codeception Testing Framework 777 Dec 12, 2022
A PHP library for mocking date and time in tests

ClockMock Slope s.r.l. ClockMock provides a way for mocking the current timestamp used by PHP for \DateTime(Immutable) objects and date/time related f

Slope 44 Dec 7, 2022
Add mocking capabilities to Pest or PHPUnit

This repository contains the Pest Plugin Mock. The Mocking API can be used in regular PHPUnit projects. For that, you just have to run the following c

PEST 16 Dec 3, 2022
Removes final keywords from source code on-the-fly and allows mocking of final methods and classes

Removes final keywords from source code on-the-fly and allows mocking of final methods and classes. It can be used together with any test tool such as PHPUnit or Mockery.

David Grudl 326 Dec 9, 2022
The modern, simple and intuitive PHP unit testing framework.

atoum PHP version atoum version 5.3 -> 5.6 1.x -> 3.x 7.2 -> 8.x 4.x (current) A simple, modern and intuitive unit testing framework for PHP! Just lik

atoum 1.4k Nov 29, 2022
Full-stack testing PHP framework

Codeception Modern PHP Testing for everyone Codeception is a modern full-stack testing framework for PHP. Inspired by BDD, it provides an absolutely n

Codeception Testing Framework 4.6k Jan 7, 2023
AST based PHP Mutation Testing Framework

Infection - Mutation Testing framework Please read documentation here: infection.github.io Twitter: @infection_php Discord: https://discord.gg/ZUmyHTJ

Infection - Mutation Testing Framework for PHP 1.8k Jan 2, 2023
:heavy_check_mark: PHP Test Framework for Freedom, Truth, and Justice

Kahlan is a full-featured Unit & BDD test framework a la RSpec/JSpec which uses a describe-it syntax and moves testing in PHP one step forward. Kahlan

Kahlan 1.1k Jan 2, 2023
Event driven BDD test framework for PHP

The highly extensible, highly enjoyable, PHP testing framework. Read more at peridot-php.github.io or head over to the wiki. Building PHAR Peridot's p

Peridot 327 Jan 5, 2023
BDD test framework for PHP

BDD test framework for PHP, inspired by Jasmine and RSpec. Features a familiar syntax, and a watch command to automatically re-run specs during develo

Daniel St. Jules 286 Nov 12, 2022
SpecBDD Framework for PHP

phpspec The main website with documentation is at http://www.phpspec.net. Installing Dependencies Dependencies are handled via composer: wget -nc http

PHPSpec Framework 1.8k Dec 30, 2022
The PHP Unit Testing framework.

PHPUnit PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. Installat

Sebastian Bergmann 18.8k Jan 4, 2023
PHP unit testing framework with built in mocks and stubs. Runs in the browser, or via the command line.

Enhance PHP A unit testing framework with mocks and stubs. Built for PHP, in PHP! Quick Start: Just add EnhanceTestFramework.php and you are ready to

Enhance PHP 67 Sep 12, 2022
Pest is an elegant PHP Testing Framework with a focus on simplicity

Pest is an elegant PHP Testing Framework with a focus on simplicity. It was carefully crafted to bring the joy of testing to PHP. Explore the docs: pe

PEST 5.9k Dec 27, 2022
SimpleTest is a framework for unit testing, web site testing and mock objects for PHP

SimpleTest SimpleTest is a framework for unit testing, web site testing and mock objects for PHP. Installation Downloads All downloads are stored on G

SimpleTest 147 Jun 20, 2022
Humbug - a Mutation Testing framework for PHP

Humbug is a Mutation Testing framework for PHP to measure the real effectiveness of your test suites and assist in their improvement. It eats Code Coverage for breakfast.

Humbug 1.1k Dec 28, 2022
Essence is a very flexible BDD style assertion framework for PHP that fits into existing PHPUnit projects nicely

Essence 1.5.1 Essence is a very flexible BDD style assertion framework for PHP that fits into existing PHPUnit projects nicely. Installation composer

bound1ess 2 Apr 7, 2015