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

Sameer Nyaupane:
PHP Test Driven Development Part 4: Enter The Mock
Sep 27, 2018 @ 17:29:29

On his HackerNoon site Sameer Nyaupane has posted part four of his series covering test-driven development in PHP. In this latest post he covers the use of mocking.

Hey there, welcome to part 4! Today we’ll learn how to mock. Mocking is a process where you create a fake instance of a real class, and test against it. This is so that, you do not have to worry about the real functionality of external dependencies inside a class. This makes unit testing a lot easier and reliable.

[...] Although PHPUnit does have mocking capabilities, it is not as full fledged as that of Mockery’s. We’ll be using Mockery for all our mocking needs.

He starts with some sample code, a simple Math class that calculates the area of a square (but doesn't implement it fully). This includes the need for an instance of a Calculate class that doesn't exist yet. He then works up a test for the Math class, mocking the Calculate class and calling the getArea method to evaluate the result. He walks you through each line of the code, sharing what's happening during test execution.

tagged: unittest mocking tutorial series part4 mockery introduction testdrivendevelopment

Link: https://hackernoon.com/php-test-driven-development-part-4-enter-the-mock-106b4fdedd00

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

Matthias Noback:
Mocking at architectural boundaries: the filesystem and randomness
Mar 06, 2018 @ 15:39:55

Matthias Noback has continued his series of posts covering mocking and testing at the "architectural boundaries" of your application. In this second post he offers two more suggestions of these "edges" where mocking could be useful: filesystem interfaces and randomness.

In a previous article, we discussed "persistence" and "time" as boundary concepts that need mocking by means of dependency inversion: define your own interface, then provide an implementation for it. There were three other topics left to cover: the filesystem, the network and randomness.

He starts with the mocking of the filesystem handling and makes the recommendation of using either vfsStreamor Flysystem to provide an interface that's more easily testable. These libraries abstract away the filesystem and make it easier to mock out the functionality rather than going directly to PHP's filesystem functions. His second example, randomness, is a bit tougher as the output isn't predictable. He still recommends abstracting it out, however, and offers suggestions as to what might be possible to test.

tagged: mocking boarder architecture filesystem randomness series part2

Link: https://matthiasnoback.nl/2018/03/mocking-the-filesystem-and-randomness/

Robert Basic:
Complex argument matching in Mockery
May 09, 2017 @ 15:40:15

Robert Basic has written up a new tutorial for the unit testers out there showing how to do some complex argument matching in Mockery, a popular testing tool that offers an alternative to PHPUnit's own mocking functionality.

This past weekend I did some issue maintenance and bug triage on Mockery. One thing I noticed going through all these issues, is that people were surprised when learning about the Mockery::on() argument matcher. I know Mockery’s documentation isn’t the best documentation out there, but this still is a documented feature.

He starts with a simple mock example, mocking out AClass and defining two method criteria (one with a once and another with a never). He points out that things are not always that simple and sometime more complex argument matching is required. The Mockery:on handler allows you to pass in a closure and do more complex evaluation of the values passed in. He includes an example of this, evaluating the result of a set of arguments passed in and ensuring they're all set.

tagged: complex mocking mockery argument tutorial on method closure tutorial

Link: https://robertbasic.com/blog/complex-argument-matching-in-mockery/

BitExpert Blog:
Mocking callables in an Expressive app
May 01, 2017 @ 16: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/

Joe Ferguson:
Mocking Swift Mailer – 3 Steps to better code
Dec 22, 2016 @ 16:46:43

If you're a user of the SwiftMailer package in your application, you may have hit on issues with your unit tests with mocking the library to isolate it from the actual email sending. Joe Ferguson is here to help with some advice in his latest post on mocking the library and how he used it to solve a problem in his own code.

A few days ago an issue came across my Jira queue that mentioned odd characters showing up in the subject line of our notification system. We use SwiftMailer library which is a fantastic library for sending mail.

[...] Something was taking our twig template that we use for our email subject and changing the encoding. This is normally done when you want to convert special characters so they’re not interpreted as code blocks. The example above is showing where an apostrophe is converted to “'”, the ASCII code equivalent.

He breaks the rest of the post into 3 steps (well, really 4 but there's a 2.5 in there) that he followed to mock the library out appropriately and be able to test the message sending without actually having to send. Code examples are included of both the code doing the sending and the test doing the mocking and verifying the subject lines on their emails (the original bug reported).

tagged: mocking unittest swiftmailer package test tutorial

Link: https://www.joeferguson.me/mocking-swift-mailer-3-steps-to-better-code/

Lanre Adelowo:
A Subtle Introduction to Mocking
Dec 08, 2016 @ 18:16:10

Lanre Adelowo has a recent post to his site introducing you to some of the basics of "mocking" in unit testing, some of the reasons to use it and plenty of examples of it in action using the Mockery library.

Mocking is simply the process of replacing an object with a fake that can act as a replacement. [...] The major reasons why we mock are Dependency elimination and removal of side effects. Think things like databases, 3rd party API requests and network requests, code that has to hit the filesystem.

This stuffs aren’t always guaranteed to be available or can prove tedious to set up (an internet connection for example) and even when they are (a logger that writes to the filesystem for example), they always tend to make your tests run extremely slow.

After covering some of the basics of mocking he talks about how they differ from stubs and how to get Mockery installed. He illustrates some of the basics concepts with a "user search" functionality based on a API request to GitHub. He's writing the results to the file system (via a Logger) so this is the main target of the mock. He creates a mock "FileSystem" class the Logger is refactored to use. He then mocks this dependency out and defines a "shouldReceive" handler for the call to write the log. This replaces the need for the test to write to the file system and makes it possible to test things in isolation rather than relying on the environment.

tagged: mocking introduction unittest mockery tutorial

Link: http://lanreadelowo.com/blog/2016/12/02/a-subtle-introduction-to-mocking/

Konstantin Kudryashov:
Conceptual difference between Mockery and Prophecy
Jan 14, 2014 @ 16:47:20

In a new post to his site today Konstantin Kudryashov takes a look at two PHP testing tools and the differences/similarities between them - Mockery and Prophecy. Mockery is a mocking tool created by Pádraic Brady to make mocking simpler and Prophecy is more of a mocking framework, both for use in PHP unit testing.

Today I’ve been asked twice what’s the difference between Mockery and Prophecy just to suddenly discover that I didn’t clarify this aspect never before. Well, that’s about time. If we were to remove all the syntactical and implementation differences between two libraries what we’ll be left with is one really big conceptual difference and it’s the fact that in contradiction to Mockery, Prophecy puts messaging (aka how objects communicate) before structure (aka when objects communicate).

He starts with a sample class (the usual "calculator" example) and shows how it would look to mock it out with each tool, setting return values for both the "getRating" and "setRating" methods. He enhances the tests a bit more to include an event dispatcher and raising an event. The approach is similar, but Prophecy uses something called "message binding" to more effectively handle changes to the class under test.

tagged: difference mockery prophecy unittest mocking framework

Link: http://everzet.com/post/72910908762/conceptual-difference-between-mockery-and-prophecy

QaFoo.com:
Mocking with Phake
Mar 13, 2013 @ 17:53:26

On the QaFoo blog today there's a new tutorial posted showing you how to make unit test mocks with Phake, a testing tool that works a bit differently that other options (PHPUnit's own mocking and Mockery).

The use of Mock and Stub Objects is an important skill to learn when using Test Driven Development (TDD). Mock objects allow you to replace dependencies of an object with lookalikes, much like crash test dummies are used during automobile safety tests so humans aren't harmed. [...] Using Mocks in PHPUnit tests means using the built-in MockObjects library for quite some years. In the last years two contenders emerged that can be used as optional dependencies in PHPUnit. [...] This blog post introduces Phake, because it works quite differently than both PHPUnit Mock Objects and Mockery.

They include a code example of how to create mocks with Phake, showing it's different approach to defining the mocked methods. They explain each part of the code, detailing the use of the "when", "thenReturn" and "verify" methods. You can find out more about Phake and see other examples in the project's documentation.

tagged: mocking unittest phake library tutorial introduction

Link:

Zumba Engineering Blog:
Mocking Singleton PHP classes with PHPUnit
Nov 26, 2012 @ 15:51:04

On the Zumba Engineering blog today Chris Taylor has a new post about mocking in PHPUnit, specifically how to handle those pesky Singleton methods lurking around your codebase.

In many of our projects, utilities and vendor classes are implemented with a singleton pattern. [...] In this post, we’ll cover a nice way to inject a PHPUnit mock object for use in testing methods that utilize singleton classes.

He starts by introducing mocking and how to use mock classes in PHPUnit with a simple "sayHello" example. Adding on another layer, he creates a "SomeclassMock" class, defining its own "expects" and "cleanup" methods. This class forces the Singleton method to act more like a regular non-static method and "resets" it after each use.

tagged: mocking phpunit class singleton expects cleanup tutorial

Link:


Trending Topics: