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

thePHP.cc:
Testing Keeps Me From Getting Things Done
May 25, 2017 @ 09:52:29

On thePHP.cc site they have a new post that tries to refute a common claim from developers when it comes to testing: testing keeps me from getting things done. The post is a response to an email to the group about testing asking where the real value is in applications versus libraries/tools.

To successfully develop software means to work target-oriented. These targets should be derived from acceptance criteria that are reconciled with the business. Without clear targets – we mean at a task level, not project or annual targets – the developer runs the risk of getting lost in work. Most importantly, he does not know when he is done with a task.

It is prudent to document and verify acceptance criteria through automated tests. One way or another, the targets have to be defined before production code gets written. This is test-driven development, whether you want to call it that or not.

The response goes on to talk about how, with tests written after the code has already been written (legacy code), it's not always clear what the original intent was resulting in lost context. It also compares two of the main types of testing - integration and unit - and the place each has in an overall testing strategy.

tagged: testing unittest reply integration opinion application

Link: https://thephp.cc/news/2017/05/testing-keeps-me-from-getting-things-done

QaFoo Blog:
Testing the Untestable
May 02, 2017 @ 12:32:55

On the QaFoo blog there's a new post sharing a method for testing the untestable - file upload handling in your application.

A long time ago I wrote a blog post about Testing file uploads with PHP where I have used a CGI PHP binary and the PHP Testing Framework (short PHPT), which is still used to test PHP itself and PHP extensions.

Since the whole topic appears to be still up-to-date, I would like to show a different approach how to test a fileupload in PHP in this post. This time we will use PHP's namespaces instead of a special PHP version to test code that utilizes internal functions like is_uploaded_file() or move_uploaded_file().

They update the previous method to use the namespacing built in to PHP to "trick" the test into using a method from a local namespace first. The provide the code they'll be testing and a unit test to try and evaluate its result. The tutorial then shows how to use the namespaces to define is_uploaded_file and move_uploaded_file functions that override the defaults. These are used instead of the base level PHP ones making it easier to test the results of the mocked functions rather than the originals.

tagged: testing untestable fileupload unittest namespace tutorial

Link: https://qafoo.com/blog/102_testing_the_untestable.html

BitExpert Blog:
Mocking callables in an Expressive app
May 01, 2017 @ 11:18:28

On the BitExpert blog Stephan Hochdörfer shows you how to mock callables in a Zend Expressive application based on a way he found during his own unit testing.

While working with Zend Expressive, a PSR-7 middleware microframework, I wanted to apply some unit testing with a nice coverage to my middlewares. Middlewares are called by the __invoke method if you provide them as an object and not as a closure. [...] Additionally, my middleware implementation does some stuff, but the middleware itself does not return a response, which is fine. Instead, my implementation calls the $next middleware in line.

He finishes the post with a quick example of how to mock out this $next call in his testing using the createPartialMock functionality in PHPUnit. He uses this method to create a mock that covers the __invoke method and returns a ResponseInterface instance of his choosing.

tagged: zendexpressive mocking phpunit unittest invoke callable testing tutorial

Link: https://blog.bitexpert.de/blog/mocking-callables-in-an-expressive-app/

Gundars Meness:
Unit Testing - The Big Picture
Apr 24, 2017 @ 11:56:50

If you're still new to the world of testing in your applications, you should give this new guide from Gundars Meness a read. He's done a great job of providing "the big picture" of testing - why to do it and what it is.

This is not a crash course of what characters one needs to type in his code editor to produce unit tests. This is fuel the brain requires before attempting such actions.

The subject of Unit Testing is not as simple as one might think. Many of us, developers, go into unit testing based on pressure from clients, peers, colleagues, our heroes and so on. We quickly learn the value of it, and, once the tech setup is done, there is a tendency to forget the big picture, if it was ever learnt. This article will provide a short insight into what is and isn’t unit testing in PHP and in general, and unit test place in the quality assurance realm.

He then breaks up the article into a few different sections, each with a paragraph or two, covering different testing related topics:

  • What is testing?
  • What really is testing?
  • What is Unit Testing?
  • How to write a Unit test?

There's some great suggestions in here, for both those new to testing and those still trying to figure out some good practices.

tagged: unittest introduction bigpicture testing

Link: http://gundars.me/php/unit-testing-php-big-picture/

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