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

Nikola Posa:
Testing web API clients using Guzzle Mock Handler
Apr 09, 2018 @ 09:43:06

Nikola Posa has a quick post to his site showing how to use a mocked up HTTP request handler - in this case Guzzle - for testing web API clients. These scripts make live HTTP requests to remote APIs as a part of their functionality but this presents a dilemma for testers. Unit tests should not reach out to external sources...and that's where the mock comes in.

Whether you're writing a client for your own web API to offer it to users or you're simply implementing integration for a 3rd-party API in your system, it is important to test it to make sure your client is capable of handling actual API responses correctly.

Testing web API clients is mostly about checking how they deal with responses received after sending requests to API endpoints, and for your unit tests, you introduce test doubles to simulate API calls instead of executing real HTTP requests.

He starts with a quick note about the usual way he's seen this issue worked around, creating a separate mocked class instead of using the actual tool. Fortunately, if you're a Guzzle user, there's a tool that comes with the HTTP client that can be used in your unit tests in much the same way as a normal Guzzle instance: the Guzzle MockHandler. He includes some example code showing how to use this class and inject it into your client and use it in much the same way as a normal client instance.

tagged: guzzle http testing mock unittest handler tutorial

Link: https://blog.nikolaposa.in.rs/2018/04/07/testing-web-api-clients-using-guzzle-mock-handler/

Matthias Noback:
Mocking the network
Apr 04, 2018 @ 11:19:06

Matthias Noback has continued his series about "mocking the edges" in your unit testing with this new post. In it, he talks about mocking "the network", those places where your application reaches out to external services to access data or perform other operations.

In this series, we've discussed several topics already. We talked about persistence and time, the filesystem and randomness. The conclusion for all these areas: whenever you want to "mock" these things, you may look for a solution at the level of programming tools used (use database or filesystem abstraction library, replace built-in PHP functions, etc.). But the better solution is always: add your own abstraction.

[...] The same really is true for the network. You don't want your unit tests to rely on a network connection, or a specific web service to be up and running. [...] The smarter solution again is to introduce your own interface, with its own implementation, and its own integration test. [...] Though this solution would be quite far from traditional mocking I thought it would be interesting to write a bit more about it, since there's also a lot to say.

In his example he shows the use of a file_get_contents call to fetch stock information. He introduces a ExchangeRateService interface with a getFor method to provide structure for the "wrapper" around the network call. He then covers the idea of an "anti-corruption layer" to change up the interface to use models instead of just a string value (code included). He ends the post talking about the inversion of the dependency - the option to have a job pull the value out-of-band and then have the application use that value.

tagged: mock testing unittest network connection interface inversion

Link: https://matthiasnoback.nl/2018/04/mocking-the-network/

Ivan Enderlin:
How Automattic (WordPress.com & co.) partly moved away from PHPUnit to atoum?
Mar 22, 2018 @ 12:08:37

In a post to his blog Ivan Enderlin talks about a move that his team at Automattic (the company behind WordPress) made away from using PHPUnit for their application testing over to atoum and some of the reasoning behind it.

Few months ago at tagged: wordpress testing unittest atoum phpunit comparison migration

Link: https://mnt.io/2018/02/26/how-automattic-partly-moved-away-from-phpunit-to-atoum/

Frank de Jonge:
Being in control of time in PHP
Mar 08, 2018 @ 10:49:18

Frank de Jonge has a new post to his site covering something that always seems to be a difficult topic in development: time. In his post he suggests that date and time handling in your application is a "dependency" that could be difficult test.

When developers talk about the infrastructural boundaries or external dependencies they often talk about databases and third-party integration. They're the first thing we'll put behind an interface so we can stub them out during our tests. This gives us some control over them. It's become relatively easy to spot these dependencies because we do it frequently. They're the usual suspects.

However, some "dependencies" are much harder to spot. They even live right inside the standard library of PHP and often manage to seep through the cracks. Date/Time handling is such a thing. So what's the problem and how do we fix it?

He goes on to talk about date/time handling programming languages in general and how its variance can can cause issues that might be out of our control. He suggests that when time "gets the best of you" you should opt to be more specific in your date/time handling (the cause is usually precision). He then gets into some code examples of how to "control time" by reducing the impact that direct date/time handling could have on your application. He also includes an example of testing this handling and finishes with the idea of "consuming time as a service".

tagged: datetime control test unittest example dependency

Link: https://blog.frankdejonge.nl/being-in-control-of-time-in-php/

Matthias Noback:
Mocking at architectural boundaries: persistence and time
Feb 22, 2018 @ 11:07:35

In a new post to his site Matthias Noback takes a look at unit testing your code and how it can be "dangerous" if you use mocking/doubles in the wrong way (not effective testing). Instead, he makes the recommendation to mock at architectural boundaries, specifically looking at mocking persistence and time handling.

More and more I've come to realize that I've been mocking less and less. The thing is, creating test doubles is a very dangerous activity.

[...] For example, by creating a test double for the EntityManager, we're assuming that it will work well with any objects we'll pass to it. If you've ever debugged an issue with an EntityManager, you know that this is a bad assumption. Anything may go wrong: a mistake in the mapping, missing configuration for cascading persist/delete behavior, an issue with the database credentials, availability of the database server, network connectivity, a missing or invalid database schema, etc.

He then gets into the concepts behind mocking across the "architecturally significant boundaries" and what kind of functionality this involves. He then gets into the two different examples sharing some of the basic concepts and test examples for evaluating persistence and time handling. He finishes up with a look at some of the potential consequences ("outcomes" is really a better word) of refactoring your tests and code to follow these ideas.

tagged: mock unittest architectural boundary persistence time tutorial

Link: https://matthiasnoback.nl/2018/02/mocking-at-architectural-boundaries-persistence-and-time/

Alejandro Celaya:
Mutation testing with infection in big PHP projects
Feb 19, 2018 @ 09:39:58

Alejandro Celaya has a post on his site that shows how to use a less well-known testing tool - mutation testing - to test for variations on the "good" and "bad" data paths. In this article he makes use of the infection library that replaced the previously active Humbug library.

There's no doubt that having tests in a project allows you to find potential bugs earlier and more easily.

Lots of OSS projects require a minimum code coverage in order to accept new pull requests from contributors, and proprietary projects also tend to have some sort of continuous integration workflow which requires certain metrics to be fulfilled in order to get builds passing. However, the code coverage can lead to a false sense of security, which makes you think that if a certain class has a 100% code coverage, it is also 100% bug-free.

This is not always true since you could be calling a method and yet not being properly testing its output or its real behavior. The code coverage will mark it as covered, but you might introduce a bug and still have a green test. This is where mutation testing comes in.

He starts by briefly introducing the concepts of mutation testing and showing how to get the infection library installed and configured. He then gives a guide on running the tool and some of the command line options that can be used to configure threading, having it only run on covered code and setting the log verbosity. He then offers some advice on troubleshooting the use of the tool and how phpdbg is used to generate reports.

tagged: unittest mutation testing infection tutorial project

Link: https://blog.alejandrocelaya.com/2018/02/17/mutation-testing-with-infection-in-big-php-projects/

Laravel News:
Defense Programming: Anticipating Failures with Tests
Feb 14, 2018 @ 09:45:25

On the Laravel News site there's a tutorial posted that makes some suggestions about how to anticipate application failures by using effective unit testing.

When you start working on a new feature, it is wise to plan out not only how it is expected to work, but what happens if something fails. Taking the time up front to anticipate failure is a quality of a great developer.

[...] Since we don’t know when a dependency might fail, it’s best to plan for failure by having tests so we can be more confident in failed states. Laravel can help us write tests that plan for failure using real-time facades.

In their example, they create a simple "article" repository class that makes use of a HTTP client to fetch the information for each article (by ID). In this case the client is Guzzle. They then add a singleton to the configuration to fetch the API class and show how to implement it in a controller. With this structure, they then move on to testing for failure via real-time facades and mocking a Guzzle response using a "Client" facade instead of calling it directly.

tagged: failure test defensive programming unittest laravel tutorial

Link: https://laravel-news.com/defense-programming-anticipating-failures-tests

Robert Basic:
Mockery partial mocks
Feb 05, 2018 @ 11:18:08

Robert Basic has a quick post to his site where he shows how to use partial mocks in Mockery, a useful tool for unit testing in PHP applications.

In dealing with legacy code I often come across some class that extends a big base abstract class, and the methods of that class call methods on that big base abstract class that do an awful lot of things. I myself have written such classes and methods in the past. Live and learn.

One of the biggest problems with this kind of code is that it is pretty hard to test. The methods from the base class can return other objects, have side effects, do HTTP calls…

He gives an example of a model that includes a method returning a database connection. In the child class of this the method that he's wanting to test includes a call to this method, making it difficult to test in isolation. He then shows how to make a partial mock of the child class that, be definition, returns a mocked PDO instance instead of the real PDO instance. All other methods will be passed through to the real class.

tagged: mockery unittest partial mock class abstract tutorial

Link: https://robertbasic.com/blog/mockery-partial-mocks/

Anna Filina:
Testing Legacy PHP Scripts
Jan 30, 2018 @ 11:56:23

Anna Filina has a quick post to her site with some recommendations around testing legacy PHP scripts giving an example of a challenge to test a controller in isolation from the rest of the application.

I gave myself a challenge: to test a legacy "controller" in isolation, yet with minimal impact on the original code.

She starts with the example code she'll be testing and then works through the steps to effectively test it:

  • isolating it from the other functionality in the application
  • mocking a statically called method
  • requiring necessary files
  • executing the controller under test

The post ends with the test class she created showing how to evaluate the result of a call with one invoice in the billing system. She makes one comment at the end to answer the question "why not just refactor" but points out that, especially in larger legacy applications, that's just not always an option.

tagged: testing legacy script tutorial isolation mock unittest phpunit

Link: https://afilina.com/testing-legacy-php-scripts

Brandon Savage:
Don’t write useless unit tests
Jan 17, 2018 @ 10:44:42

Brandon Savage has a quick post to his site sharing some advice around the testing of your application, more specifically around unit tests: don't write useless unit tests. He starts with an example of a test that, while moving the project closer to the 100% coverage number, is mostly useless.

Too often, in the search for 100% unit test code coverage, I see tests like this get written. They don’t serve a practical purpose, except to meet the test coverage goal. Worse, they don’t actually improve the quality of the application.

Instead of writing a unit test here, we would be better served by writing an integration test, or a functional test. These tests would require us to interact directly with the database, but would provide far more valuable information about the health and status of our application. A useless unit test provides us with little if any benefit; a useful functional test provides us with tremendous advantages.

He includes the code for the test and talks about what's wrong with the approach and how it could potentially be handled better. He suggests that writing good, useful tests requires both skill and determination and the avoidance of tests that actually increase the quality of the overall test suite.

tagged: useless unittest tutorial example functional test

Link: https://www.brandonsavage.net/dont-write-useless-unit-tests/