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

Freek Van der Herten:
Handcrafting mocks
Dec 13, 2018 @ 15:15:12

In a recent post to his site Freek Van der Herten talks about "handcrafting mocks" in your unit testing. In his example he shows the creation of custom mocks rather than using one of the current mocking test tools.

In an application I was working on I wanted to implement automated tweets. Of course, this logic should also be tested. In this blogpost I'd like to show you how you can easily handcraft your own mocks.

In his application, he wanted to be able to send tweets to Twitter when certain events happened. He starts with a bit of set up showing how to use this library to set up the OAuth connection between your application and Twitter account. He then shows the class that will make the actual tweet and how to use event handling to send the message when a new blog post is published. With this all in place, he starts in on the testing, showing the creation of the custom mock (so tweets aren't actually sent) and how to use it to test that a tweet was sent. He finishes the post with a mention of a possible refactoring: using an interface instead of extending a class to make the testing more structured.

tagged: mock unittest testing tutorial custom handcrafted

Link: https://murze.be/handcrafting-mocks

Larry Garfield:
Don't use Mocking libraries
Sep 21, 2018 @ 16:02:10

Larry Garfield has written up a post with a somewhat controversial headline, especially for anyone that's done any kind of unit testing on a larger codebase. His suggestion is to no use mocking libraries and some other techniques that can replace them.

I am all for testing. [...] There's a lot of opinions on what constitutes a "good" test, of course, and much is subjective to the type of code you're working on. However, since the release of PHP 7 I've found that while writing tests... I am never using a mocking library. In fact, I'm going to go as far and say that you should never use a mocking library in PHP 7.

Before all of you gasp, clutch your pearls, and send ninja hit squads after me, let me justify that position.

He starts off by defining what a "mock" is a more general sense and then, more specifically, how mocking libraries are mostly implemented in PHP. He covers the DSL (domain specific language) knowledge that's required to use most of them and how something already included in PHP 7 - anonymous classes - could be a viable alternative. He goes on to show examples of using this method rather than a mock for simple object handling and even recommends making an actual class (just for testing) if the need is there. He ends the post talking about the "upper bounds" of when this might not be as useful and how this can actually be good (using it as an indicator that you need to refactor the main code to simplify).

tagged: mocking mock library testing unittest opinion anonymous class

Link: https://steemit.com/php/@crell/don-t-use-mocking-libraries

Tomas Votruba:
How to Turn Mocks from Nightmare to Solid Kiss Tests
Jun 13, 2018 @ 17:36:48

In a new post to his site Tomas Votruba shows you how to make your unit test mocks better with an easier and clearer way to use them. This simplification makes use of something PHP itself is already able to do: create anonymous classes.

At the time being, there is only 1 post about anonymous classes in tests (thanks to Matthieu!). Compared to that, there are many PHP tool made just for mocking: Prophecy, Mockery, PHPUnit native mocks, Mockista and so on. If you're a developer who uses one of them, knows that he needs to add proper annotations to make autocomplete work, has the PHPStom plugin that fixes bugs in this autocomplete and it works well for you, just stop reading.

This post is for developers who struggle with mocking and have a feeling, that they're doing something wrong.

He starts with an example of a test that creates a mock for an external request to the Heroku service using PHPUnit's mocking tools. He points out that this requires extra knowledge of the mocking methods and functionality to accomplish, potentially making it difficult to understand for those new to the tool. He then shares a refactor of the same test, this time making use of an anonymous class to mock out the needed findByCategoryId method and return a response. He ends the post pointing out that, as a side effect of this refactoring (and other interface refactoring) you'll create more SOLID code and it can help make it easier to maintain in the future.

tagged: tutorial mock unittest test anonymous class tool

Link: https://www.tomasvotruba.cz/blog/2018/06/11/how-to-turn-mocks-from-nightmare-to-solid-kiss-tests/

Nikola Posa:
Testing web API clients using Guzzle Mock Handler
Apr 09, 2018 @ 14: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 @ 16: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/

Matthias Noback:
Mocking at architectural boundaries: persistence and time
Feb 22, 2018 @ 17: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/

Robert Basic:
Mockery partial mocks
Feb 05, 2018 @ 17: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 @ 17: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

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 4)
Jan 23, 2018 @ 16:21:14

Mark Baker has returned with a new part of his series looking at the use of anonymous classes and closures as an alternative to the typical test mocking functionality. In this latest part (part four) he talks more about the "SpyMaster" class created in the previous article and how it can be refactored to provide the spies with a "mission".

In a prior article in this series, I described the use of a SpyMaster Class to create proxy spies as anonymous classes, that allow external visibility (and potentially update) of protected and private properties within an object. The same basic principle of a spy can also be used to create a proxy that gives us access to execute the private and protected methods of an object.

[...] Unlike the original SpyMaster that I wrote about last July, we’re going to take a slightly different approach here, providing our spies with a “mission”.

He first shares the code for the old class and covers why it was useful. He then moves on to the refactor, showing how it defines the "mission" (what to mock) and an "invoker" that helps with the actual execution. He gives an example of this new class in use, performing an "infiltration" on a sample object and calling previously protected methods directly.

tagged: closure anonymous class alternative mock tutorial part4 series

Link: https://markbakeruk.net/2018/01/23/closures-anonymous-classes-and-an-alternative-approach-to-test-mocking-part-4/

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 3)
Sep 19, 2017 @ 16:58:39

Mark Baker has posted the third part of his series looking at an alternative way to handle mocking in the tests for your PHP application. In this latest part of the series he shows how to modify one of PHPUnit's own mocking examples to use an anonymous class.

I have heard people say that you shouldn’t test abstract classes or traits, only the concrete classes that implement or use them. I don’t follow that approach: unit testing is all about testing in isolation from anything that might affect those tests. Testing a concrete class that implements an abstract one, or uses a trait, means that the abstract class or trait is no longer fully isolated, but is being tested within the scope of the whole of that concrete class. We should still always test concrete classes as well; but we should also test the abstract classes and traits as individual units.

So just how do we test something that cannot be instantiated on its own?

He shares one tactic that some developers use - a class designed only for testing - but suggests that this "pollutes" the codebase. Instead he shows how to replace mocking for traits and abstract classes with an anonymous class that's more "disposable". He also shows how to modify this approach to handle calling protected methods in the class the anonymous class extends.

tagged: closure anonymous class alternative mock tutorial part3 series

Link: https://markbakeruk.net/2017/09/18/closures-anonymous-classes-and-an-alternative-approach-to-test-mocking-part-3/


Trending Topics: