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

Laravel News:
Introduction to Seeding Data in Testing
Apr 10, 2017 @ 10:42:26

On the Laravel News site they've posted an introduction to seeding data in testing to help make your Laravel application testing easier and see "more correct" results.

Since seeding was released in Laravel 5.1, testing has become easier and quicker.

You can have ten users with each having a post or 1000 users with one or more posts inserted before the testing begins. In this tutorial, you will create a test case to test the user model and a seeder to seed ten users, and each is following one user into the database.

The tutorial starts with a migration to create a "users" table including a "follow user ID" field that tracks which user another is following. Next up is the creation of the User model with the methods to create the "follow" links between users. The make:seeder command is then used with this model to generate the seeder class and make 10 users with faked information. The db:seed command is used to execute the seeder and populate the data. Finally an example test case is created, first just testing that 10 users were created then refactored to test links between the users and the follow/unfollow functionality.

tagged: laravel seed data testing migration tutorial unittest model

Link: https://laravel-news.com/seeding-data-testing

Russell Walker:
Is Best Practice Actually Poor Practice? Dependency Injection, Type Hinting, and Uni
Apr 05, 2017 @ 13:26:03

Russell Walker has a post to his site sharing his thoughts defending dependency injection, type hinting and unit testing against some of the common objections.

I've recently been in discussion with a colleague who thinks that dependency injection (DI) is over-used and, in cases where the dependency is a concrete class, unnecessary (in the latter case, he advocates simply creating new objects on the fly).

[...] In my opinion, this line of thinking is misguided, but he sent through some links to pages that he felt supported his point of view (including Tony Marston's rant on DI, and the Laravel documentation about 'facades' - which are actually used as an alternative syntax for the service locator [anti-]pattern). I genuinely wanted to understand the reasoning behind his point of view, as it flies in the face of just about everything I have ever read regarding best practice in PHP development. After reading those resources he sent though, I began to notice some misconceptions about what unit testing actually is, as well as confusion about the difference between code that is "strongly typed" (usually good) and "tightly coupled" (usually bad), and also a tendency to blame the wrong thing when problems arise.

He then breaks the rest of the post down into a few of the common objections and makes an attempt to set the record straight:

  • Not All Automated Tests Are Unit Tests
  • Using Mocks to Test in Isolation
  • What, Never Ever Create Objects on the Fly?
  • What About Those Laravel Facades?
  • Hidden Dependencies and Other Dangers
  • Strongly Typed is not Tightly Coupled

He ends the post with "another reason" that there could be issues with developers dismissing best practices in their development - a misunderstanding of the principle and how to correctly implement it.

tagged: bestpractice dependencyinjection typehint unittest opinion

Link: http://russellscottwalker.blogspot.co.uk/2017/03/is-best-practice-actually-poor-practice.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/

PhpStorm Blog:
Working With PHPUnit and PhpStorm
Mar 23, 2017 @ 11:50:12

On the PhpStorm blog (from JetBrains) Gary Hockin reflects on a post from Adam Wathan with tips for combining PHPUnit and PhpStorm for more effective debugging.

Community stalwart and Laravel aficionado Adam Wathan blogged on his PHPUnit workflow in Sublime text.

Gary then goes through the points in Adam's post and shows how they can (mostly) be accomplished directly in PhpStorm:

  • Generating unit test boilerplate for a class
  • Using "snippets" to create shortcuts for reusable code
  • Running the tests in just one file directly from the IDE

Each section comes with a brief description and animated screen grabs showing the flow of the setup and use for each.

tagged: phpstorm debugging unittest feature generation snippets singlefile tutorial

Link: https://blog.jetbrains.com/phpstorm/2017/01/working-with-phpunit-and-phpstorm/

QaFoo:
How to Perform Extract Service Refactoring When You Don't Have Tests
Mar 22, 2017 @ 10:42:39

On the QaFoo blog they've posted an article sharing advice about refactoring to extract logic to services when there's no testing to cover the code.

When you are refactoring in a legacy codebase, the goal is often to reduce complexity or separate concerns from classes, methods and functions that do too much work themselves. Primary candidates for refactoring are often controller classes or use-case oriented service classes (such as a UserService).

Extracting new service classes is one popular refactoring to separate concerns, but without tests it is dangerous because there are many ways to break your original code. This post presents a list of steps and checklists to perform extract service when you don't have tests or only minimal test coverage. It is not 100% safe but it provides small baby-steps that can be applied and immediately verified.

The article talks about some of the primary risks when performing this kind of refactoring and how their extract method recommendations could case some of those issues. The tutorial then breaks down the process into the small steps:

  • Step 1: Create Class and Copy Method
  • Step 2: Fix Visibility, Namespace, Use and Autoloading
  • Step 3: Check for Instance Variable Usage
  • Step 4: Use New Class Inline
  • Step 5: Inline Method
  • Step 6: Move Instantiation into Constructor or Setter
  • Step 7: Cleanup Dependency Injection

While that seems like a lot of steps to take, they're all pretty small. They include a series of code snippets giving you an example to work from, making these small steps to refactor current functionality into a Solr service class.

tagged: tutorial refactor extract service tutorial unittest example code

Link: https://qafoo.com/blog/099_extract_service_class.html

Mark Baker:
Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 1)
Mar 06, 2017 @ 11:12:04

On his site Mark Baker has posted the first part of a series of articles covering the use of closures and anonymous classes in testing and mocking. In this first part of the series he focuses on introducing some of the basics of the topics to be covered and what the closures/anonymous classes can replace.

Since their first introduction with PHP 5.3, Closures have proven an incredibly useful feature for writing simple callback code, making it cleaner and more intuitive. Anonymous Functions can be used inline for many of the array functions or assigned to a variable as a Lambda that can be referenced many times in different places in your code.

[...] But this isn’t an article about the differences between Anonymous and Lambda Functions and Closures [...] Instead, I want to take a look at binding Closures to objects as a first step to demonstrating an alternative approach to test mocking.

He goes on to talk about the mocking the PHPUnit already includes, other libraries that help with mocking/stubs but then pushing those off for the focus of the article - the use of the closures/anonymous classes. He gets into some details about how PHP handles closures internally and how to bind a closure to a class or object instance (via the bindTo function). He then attaches this to an object and shows how to create a "snooper" to work with an object, perform some processing and return some values from it.

tagged: closure anonymous function tutorial testing unittest phpunit snooper

Link: https://markbakeruk.net/2017/03/05/closures-anonymous-classes-test-mocking-1/

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

Alejandro Celaya:
Run PHPUnit tests inside a docker container from PhpStorm
Feb 02, 2017 @ 11:14:04

Alejandro Celaya has a tutorial posted on his site showing you how you can improve your PHP workflow by running your unit tests in a Docker container from inside of PHPStorm.

Docker is, without any doubt, the trending tool these days. Everybody wants to use it, because it is very useful, allowing to easily generate development environments for any kind of application.

A couple months ago I started working with docker myself (it has taken me a while, I know), and now I can't imagine working without it. I started using it at work, but now I'm migrating all of my OSS projects too.

With Docker involved things get a bit more tricky when it comes to running your unit tests directly from PHPStorm (unlike local where it's just a few clicks away). Thankfully recent versions of PHPStorm come with a feature in the "Build, Execution, Deployment" that lets you define the location of the Docker executable. Then you'll need to set up a remote interpreter to link to the PHP binary then take that and link it back to the Docker installation. He ends the post showing how you can ensure it's working complete with a screenshot of the console showing the test results.

tagged: phpunit docker phpstorm container ide tutorial unittest

Link: https://blog.alejandrocelaya.com/2017/02/01/run-phpunit-tests-inside-docker-container-from-phpstorm/

ThePHP.cc:
Refactoring to PHP 7
Jan 31, 2017 @ 10:52:42

On thePHP.cc blog today there's a new post sharing some helpful hints related to refactoring your application to PHP 7 written up by a friend of the group, Tim Bezhashvyly.

Recently I have migrated a relatively large codebase from PHP 5.6 to PHP 7 and would like to share some of my learnings. To get the most out of this article, you should be familiar with scalar type declarations (and return type declarations). To learn about these and other features of PHP 7, I recommend the "PHP 7 Explained" eBook.

He makes the recommendation of a bold first step: enabling the strict typing on every file in your application to enforce the typing of all values. Next he recommends running your current test suite to see where the failures are. Changes are pretty high that you'll find issues with type switching and magic method handling. He suggests a method for migrating your code effectively to PHP 7: a test-driven migration. This focus works fine if your coverage is good but unless you're exercising all parts of your codebase things will unfortunately be missed.

He also points out some other changes you can make with this update including the removal of some PHPDoc annotations (you'll know the type for sure now) and modifications that may need to be made to current mock objects in your tests. There's a few other smaller things he recommends looking out for as well including the use of the "silencer" operator and exception changes.

tagged: refactoring php7 testdriven unittest testing migration strict types

Link: https://thephp.cc/news/2017/01/refactoring-to-php7