Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

QaFoo Blog:
Refactoring Singleton Usage to get Testable Code
Jul 11, 2017 @ 12:22:07

The QaFoo.com blog has a new post sharing a helpful hint on refactoring singletons to make them more testable. Singletons and notoriously difficult to test due to how it can potentially return an unexpected version of an object.

So your code base is littered with singletons and using them? Don't worry, you can start refactoring them out of your code base class by class and introduce increased testability at every step. This strategy is very simple to implement and the probability of breaking your code is very low, especially when you are becoming more experienced with this technique.

They give an example of a service class that uses a singleton to get an instance of the Solarium_Client class via a static method call. They show how to refactor this out into a separate method and then use the "lazy initialization" pattern to only use the singleton if the property isn't already defined. This then allows you to use a setter to inject your own client during testing (a mock most likely).

tagged: refactor testing unittest mock singleton property lazy initialization

Link: https://qafoo.com/blog/107_refactoring_singletons_testability.html

Adam Wathan:
Detecting Out of Sync Mocks in Mockery
Apr 05, 2017 @ 11:14:41

Adam Wathan has shared a new post on his site with advice on finding out-of-date mocks when using the Mockery mocking tool in your testing.

If you're not careful, it's easy to find yourself in a situation where a test double has gotten out of sync with the actual class or interface it's mocking.

In this quick screencast (taken from my Test-Driven Laravel course), I walk through how I use a little-known Mockery feature to help track down these issues and make sure I'm not mocking methods that don't exist.

The quick screencast (about 4 minutes) gives an example of locating the issue when a "Ticket" class is refactored. While the tests still pass, it can cause issues in testing and can be difficult to find. Mockery comes with a configuration option (in 1.0 alpha) to disable the mocking of methods that don't exist on the original object. He shows how to disable this feature and what the resulting error looks like when the tests are run.

tagged: mockery screencast unittest mock sync class disable configuration

Link: https://adamwathan.me/2017/04/03/detecting-out-of-sync-mocks-in-mockery/

Robert Basic:
PHP traits to create test doubles
Apr 04, 2017 @ 10:47:15

In a new post to his site Robert Basic shows how to make use of traits to create test doubles in your unit testing practice. He sees them as a simple method for keeping tests clean and not having mocks/fakes/etc. all over.

Keeping your application or library code well organized, easy to follow, and read is important. Your test code should not be exempt from those rules, you should follow good testing conventions.

One part of my tests that I feel like that are out of control are the test doubles. Dummies, fakes, mocks… Seems like they are everywhere and that I keep writing the same ones over and over again. I do follow some good practices on how to reduce code duplication in my tests, but these mocks… Ugh.

He starts with a simple example, showing a test that evaluates the result of a transaction being executed (true or false). However, he describes the eventual "creep" of the tests as more are added and, with each, more "transaction" object instances are required. He suggests refactoring the creation of those doubles into traits where the class they're called from can inherit them and test setup is a bit cleaner. He proposes a "trait for every double" so that they can be easily included as needed and without conflict.

tagged: traits unittest double mock tutorial example setup object

Link: https://robertbasic.com/blog/php-traits-to-create-test-doubles/

Weebly Engineering Blog:
PHPUnit - Mocking the Filesystem with vfsStream
Feb 24, 2017 @ 10:52:23

On the Weebly Engineering blog there's a new post showing you how to combine PHPUnit and vfsStream to mock out file system operations away from the actual file system.

Recently I found myself needing to write tests for a small class that read from a json file. The class needed to read a json file, validate its existence and content, provide a method to inform the user if a certain key exists, and provide a method to retrieve a value for a given key.

[...] Testing this class in isolation can be tricky because it currently has a dependency on the file system. Storing test json files to test this class would work, but is not ideal because it leaves a dependency on the file system in your tests. As with any external resource, there might be intermittent problems with the file system and could result in some flaky tests. This is where vfsStream shines.

The post includes an example class under test that pulls in the JSON files and operates on the contents. To make the testing easier they introduce vfsStream, a wrapper that allows for a virtual "file system" that can be operated on through the usual interfaces. They include an example of its use in a test on the same class making it easier to check the JSON based on a pre-defined value (essentially a mock of the file and its contents).

tagged: vfsstream unittest mock filesystem tutorial

Link: https://medium.com/weebly-engineering/phpunit-mocking-the-file-system-using-vfsstream-5d7d79b1eb2a#.vdie5rhyr

Matthieu Napoli:
Using anonymous classes to write simpler tests
Jan 24, 2017 @ 10:33:18

In a recent post to his site Matthieu Napoli shows you how to use the recently added anonymous classes functionality to help make your unit tests simpler. Anonymous classes allow for the on-demand creation of class instances without the need for the predefined class being required.

Anonymous classes were added to PHP 7. This article intends to show how useful they can be for writing tests.

He breaks it down into the three most useful places he uses them in his tests:

  • mocking classes to make it simpler to test method output
  • spies looking at properties in the mock class
  • fixture classes to help with needs such as reflection tests

Code examples are provided for each of the examples, especially the final point there.

tagged: anonymous class testing unittest mock spy fixture

Link: http://mnapoli.fr/anonymous-classes-in-tests/

Adam Wathan:
Replacing Mocks with Spies
Oct 13, 2016 @ 10:25:14

In this post to his site Adam Wathan shares a unit testing tip that can help you with more correct verification in your testing - replacing mocks with spies.

Mock objects are useful when verifying that a method was called is more important than verifying the outcome of calling that method.

[...] Mocks are a great tool, but it’s always bugged me that they force you to set expectations in advance instead of making assertions at the end like you would in a traditional test.

He gives a Laravel-based example of using Mockery to set an "expects" call on a method to ensure it's correctly called. He points out, however, that this method is more useful for checking the result of the method call and not really the fact that it was called (a slight but interesting difference). He then gives an example of testing the PHP function strrev and the phases you would go through in the testing process. He suggests that, in the creation of the mock object, you're mixing up the "setup" phase with the "assertion" phase and making them dependencies. He shows how, with a switch over to using spies instead, including the code updates for Mockery that change the mock object creation and split out the assertion from the creation.

tagged: mock spy unittest mockery assertion setup

Link: https://adamwathan.me/2016/10/12/replacing-mocks-with-spies/

QaFoo Blog:
Database Tests With PHPUnit
Oct 05, 2016 @ 11:57:36

The QaFoo blog has a new tutorial posted showing you how to work with PHPUnit and database testing for acceptance testing of your application. Acceptance testing (or integration testing) generally exercises the tests with live data from a database rather that stubbed or mocked data in true unit testing.

Most of us do not use PHPUnit solely for Unit Tests but we also write Integration or Acceptance Tests with PHPUnit. One very common question then is how to interact with the database correctly in those tests. Let me show you the different options and their trade offs...

There are multiple aspects of database tests where our decision has impact on test atomicity and test runtime. All decisions boil down to: More test atomicity leads to longer test runs, and we can buy test speed by omitting test atomicity.

They talk more about the time added for testing with database functionality included and where running them might be most appropriate (local vs on the CI server). The article then talks about one of the main decisions around doing a full data/schema reset or just removing data when the tests start or end. They then get into this last point - where the reset should happen, before or after the tests are executed. They talk in detail about each option, breaking it down into a few options: before each test, before each test class or before the whole test run. The post ends with a section talking about "mocking the database away", a method usually used in traditional unit testing but points out that this can be highly prone to errors, especially if you attempt to replace one database system with another (like replacing MySQL with SQLite).

tagged: testing acceptance database phpunit integration reset location mock

Link: https://qafoo.com/blog/090_database_tests_with_phpunit.html

Richard Bagshaw:
Prophecy
Jun 24, 2016 @ 09:11:01

Richard Bagshaw has a post to his site sharing some of his experience with the Prophecy testing tool and how it compares to Mockery for creating test doubles (mocks and stubs).

For a while now I have been using Mockery as my test double framework of choice, however recently I have been taking a look at Prophecy as an alternative.

[...] "Prophecy is a highly opinionated yet very powerful and flexible PHP object mocking framework. Though initially it was created to fulfil phpspec2 needs, it is flexible enough to be used inside any testing framework out there with minimal effort."

He then gets into some basic usage of the tool - creating a basic mock, assigning expectations and behaviors and performing the test. He steps through each line of the example explaining what's happening and what can be expected as a result. He ends the post with some final thoughts comparing Prophecy to the normal PHPUnit mocking tools and points out several other features it makes easier to work with as well.

tagged: prophecy unittest doubles mock stub example introduction tutorial

Link: http://www.richardbagshaw.co.uk/prophecy/

Full Stack Radio:
28: Jeffrey Way and Dave Marshall - "Don't mock what you don't own"
Oct 29, 2015 @ 09:32:52

The Full Stack Radio podcast, hosted by Adam Wathan, has posted their latest episode featuring guests Dave Marshall and Jeffrey Way. In this latest show they suggest you "don't mock what you don't own".

n this episode, Adam talks to recurring guests Jeffrey Way and Dave Marshall about "don't mock what you don't own". They talk about how to design code that needs to work with external services, how you should test that code, and the pitfalls you run into when you use mocks incorrectly in your test suite.

Topics mentioned include this paper suggesting you mock roles not objects and an opinion piece on why integration tests are a scam. You can listen to this latest episode either through the in-page audio player or by downloading the mp3. If you enjoy the show, be sure to subscribe to their feed and follow them on Twitter for information about when the latest shows are released.

tagged: fullstackradio podcast jeffreyway davemarshall mock object testing

Link: http://www.fullstackradio.com/28

Ahmad Hajjar:
Mocking Objects for Unit Testing in PHP Using Go! AOP
Aug 18, 2015 @ 11:55:01

In an interesting post to his blog Ahmad Hajjar shows you how to use to Go! PHP AOP framework to help mock objects in your unit tests. The Go! AOP framework provides some of the base functionality for using aspect-oriented programming techniques in your code.

These have been always very important questions in software development industry; what should I test in unit testing? And how can I make tests as small as possible, and how to avoid testing already tested code? or 3rd party libraries? [...] In principle, unit test must fail for one and ONLY ONE reason, this makes sense actually, as it complies with the S in the SOLID object-oriented design principles. [...] We can use mocks in the problem listed above, to make the unit test, real unit test, that is testing only the things that needs to be tested. [...] However, what we are going to do today is something different. OK! Why should we re-invent the wheel? the answer is : because it is simpler wheel ! also it is a wheel that uses different technology which is AOP.

He uses a simple Laravel application and the Go! framework for his testing examples. He uses the AOP functionality from Go! as the mock handling instead of something like PHPUnit's own mocking or Mockery. He shows how to configure the AOP functionality first, then creates a basic aspect class with a few interceptors for method calls. He creates an AopMocker class that adds the class requested to the mock configuration. Finally he improves the initial unit test example using these tools, building mocks for User and Post classes and making the same assertion.

tagged: unittest mock object aop aspectoriented programming goaop framework

Link: https://ashajjar85.wordpress.com/2015/08/16/mocking-objects-for-unit-testing-in-php-using-go-aop/