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

Matthias Noback:
Assertions and assertion libraries
Sep 21, 2018 @ 15:52:35

In a new post to his site Matthias Noback takes a look at the concept of assertions and some libraries including some effective ways to use them in your code for validation of values.

When you're looking at a function (an actual function or a method), you can usually identify several blocks of code in there. There are pre-conditions, there's the function body, and there may be post-conditions. The pre-conditions are there to verify that the function can safely proceed to do its real job. Post-conditions may be there to verify that you're going to give something back to the caller that will make sense to them.

[...] Sometimes the programming language itself can help with these pre-conditions: for instance, the language may support strict typing, which prevents certain types of invalid input to be provided. Some languages offer more advanced ways of defining pre-conditions, like pattern matching.

Following a brief use case for assertions (at a high level) he gets more specific to PHP and mentions two assertions libraries that could be used to add these kinds of checks to your code (in addition to PHP's own assert function). He then answers the "why use assertions?" question and some basic rules around using them:

  • don't use assertions to validate user input, use it to validate function arguments.
  • don't use assertions to validate return values from other functions.
  • don't use assertions as a replacement for exceptions.

For each of these, he provides a summary with a bit more background and code examples to help illustrate the point. He ends the post with some useful "rules of thumb" when using assertions and a reminder:

Assertions are sanity checks. When they would be left out, you should still have a correctly function application. They should never become user-facing errors.
tagged: assertion library tutorial example suggestion

Link: https://matthiasnoback.nl/2018/09/assertions-and-assertion-libraries/

Exakat Blog:
PHP assertions and their usage
Jan 18, 2018 @ 17:16:58

On the Exakat blog there's a post that covers assertions in PHP, a built-in tool the language provides to help perform simple value based evaluation against certain criteria.

PHP has a clever native debugging tool : the PHP assertions. In a nutshell, assertions are a function call to assert(), that triggers an error when a condition is not satisfied.

[...] Unlike debugging conditions, the assert() syntax has to be read in a positive way. When the condition, aka as the first argument, is satisfied, all is fine, and process goes on; when the condition is not satisfied, then an error is triggered: the message of the error is the second argument.

The post then gets into more detail about the assertions, noting that the result has to be positive and that they can be somewhat configured (basically turned on/off and the error level can be adjusted). It also covers some examples of things to test with assertions, how they should be treated as debugging and to avoid using them on resources outside the code (like database connections).

tagged: assertion usage language native tutorial introduction

Link: https://www.exakat.io/php-assertions-usage/

SitePoint PHP Blog:
What Is Snapshot Testing, and Is It Viable in PHP?
Jun 21, 2017 @ 17:28:01

On the SitePoint PHP blog they've posted another article from author Christopher Pitt. This time he talks about snapshot testing and if it's a viable way to evaluate code in PHP applications.

Ah-ha moments are beautiful and rare in programming. Every so often, we’re fortunate enough to discover some trick or facet of a system that forever changes how we think of it. For me, that’s what snapshot testing is.

You probably write a lot of PHP code, but today I want to talk about something I learned in JavaScript. We’ll learn about what snapshot testing is and then see how it can help us write better PHP applications.

He starts with a brief introduction to the technology to be used (React in Javascript) and how it could be recreated in PHP. He then covers testing interfaces, evaluating the correct functionality of frontends via various testing tools. He includes some examples of this kind of testing and how it can help a developer mentally break up functionality into components. From there he switches over to the PHP side, introducing the spatie/phpunit-snapshot-assertions package and showing how to use it to check the make up of a snapshot and test several assertions that should exist.

tagged: snapshot testing viable javascript frontend assertion tutorial

Link: https://www.sitepoint.com/snapshot-testing-viable-php/

Adam Wathan:
Replacing Mocks with Spies
Oct 13, 2016 @ 15:25:14

In this post to his site Adam Wathan shares a unit testing tip that can help you with more correct verification in your testing - replacing mocks with spies.

Mock objects are useful when verifying that a method was called is more important than verifying the outcome of calling that method.

[...] Mocks are a great tool, but it’s always bugged me that they force you to set expectations in advance instead of making assertions at the end like you would in a traditional test.

He gives a Laravel-based example of using Mockery to set an "expects" call on a method to ensure it's correctly called. He points out, however, that this method is more useful for checking the result of the method call and not really the fact that it was called (a slight but interesting difference). He then gives an example of testing the PHP function strrev and the phases you would go through in the testing process. He suggests that, in the creation of the mock object, you're mixing up the "setup" phase with the "assertion" phase and making them dependencies. He shows how, with a switch over to using spies instead, including the code updates for Mockery that change the mock object creation and split out the assertion from the creation.

tagged: mock spy unittest mockery assertion setup

Link: https://adamwathan.me/2016/10/12/replacing-mocks-with-spies/

Joe Ferguson:
Solidify Fragile Tests
Sep 05, 2016 @ 16:43:27

In this post to his site Joe Ferguson gives some advice on solidifying tests in your system that are a bit more fragile. Every test suite of any larger size has these kinds of tests - ones that usually pass but sometimes fail (and then pass just fine on the next run).

On my first week at the new job I was tasked to fix some tests that were logging data. While the fix was simple enough, by using `PsrLogNullLogger as Logger` instead of `MonologLogger` in the test, during the process I ran into another test that appeared quite fragile.

He gives an example of a fragile test, one based on a method that returns a "food" value, that would potentially fail if the data returned is not in the right order. He found the issue was with the use of the assertArraySubset check and how, thankfully, the fix was as easy as changing the assertion (and using an array_diff to help with the check).

tagged: solidify fragile tests unittest check assertion update

Link: https://www.joeferguson.me/solidify-fragile-tests/

Matthias Noback:
A better PHP testing experience Part I: Moving away from assertion-centric testing
Jul 07, 2014 @ 22:53:45

Matthias Noback has a new post today, part one in a series, looking at moving away from assertion-centric testing and more towards descriptive unit tests.

In the introduction article of this series I quickly mentioned that I think unit testing often focuses too much on assertions. [...] I used to preach these things myself too (yes, "development with tests" often comes with a lot of preaching). But now I don't follow these rules anymore. I will shortly explain my reasons. But before I do, let's take a step back and consider something that is known as the Test framework in a tweet, by Mathias Verraes.

He breaks up the rest of the article into three sections, each with a few paragraphs of description and code where appropriate:

  • Something is the case, or not
  • Only one assertion for each test?
  • Write assertions first and then work towards them?

He talks about the idea of "Arrange Act Assert" and makes some recommendations as to how to be more descriptive in your tests and make them easier to read and follow in the future.

tagged: unittest experience assertion testing descriptive

Link: http://php-and-symfony.matthiasnoback.nl/2014/07/descriptive-unit-tests/

Matthias Noback:
Test Symfony2 commands using the Process component and asynchronous assertions
Mar 24, 2014 @ 15:49:13

Matthias Noback has a new post today showing you how to test Symfony2 commands that use the Process component. More specifically, his tests revolve around the ones that use asynchronous assertions in the testing to remove weird behaviors that could be caused by multiple processes running them simultaneously.

Usually you would test a console command using the ConsoleTester class as described in the official Symfony documentation. But we can not use it in this case. We need to isolate the process in order for pcntl_fork() to work correctly, otherwise the PHPUnit test runner itself will be forked too, which will have the effect of running all the following unit tests twice (which can have very strange effects on the test results).

He shows how to use the Process component to start up a new process (the daemon) and check that the PID file exists. He includes an example of a "probe" to determine what processes are running and preventing them from stepping on each other.

tagged: symfony2 command process component asynchronous assertion unittest phpunit

Link: http://php-and-symfony.matthiasnoback.nl/2014/03/test-symfony2-commands-using-the-process-component-and-asynchronous-assertions/

NetTuts.com:
Expressive Tests with Hamcrest
Dec 06, 2012 @ 18:25:12

On the NetTuts.com site today there's a new tutorial introducing the Hamcrest validation matchers and how to use them in your PHPUnit testing to enhance both the readability and functionality of the assertions.

Hamcrest is a set of matchers for writing more expressive code. It just so happens that these matchers are especially useful when writing tests. In this article, we’ll look at Hamcrest for PHP. [...] Hamcret’s expressiveness originated with JMock, but it wasn’t until the addition of the unique assertThat() method that it was refactored into a self-contained library and independently usable in testing frameworks.

He talks about the "generations" of unit testing tools, a division based on their assertion functionality - simple, exact or using matchers. Installation instructions via PEAR are included (though there's also a composer package for it too) as well as code for an example test. More samples are given for comparing things like numeric values, strings and setting up inclusions and exclusions with the anyOf/noneOf matchers.

tagged: hamcrest unittest assertion tutorial library

Link:

PHPFreaks.com:
PCRE Regex Spotlight: K
Aug 25, 2009 @ 15:28:44

On the PHPFreaks.com blog today there's a quick new post looking at one of the special backslash strings that doesn't get talked about very much - K - but is quite powerful.

One backslash sequence that doesn’t get much attention is K. What this handy little assertion does is match the position of whatever string comes before it in the pattern, then it in essence resets the match. At that point it starts a new match with whatever comes after K from the current location in the subject string.

They include a series of PHP code examples showing how use can use it to work around some of the issues with lookbehind assertions. They also include a few benefits and drawbacks of using them over lookbehinds.

tagged: regularexpression regex assertion backslashk

Link:

Ralph Schindler's Blog:
Dynamic Assertions for Zend_Acl in ZF
Aug 17, 2009 @ 17:37:17

Ralph Schindler has a new post to his blog today looking at using dynamic assertions with the access control component (Zend_Acl) of the Zend Framework.

Over the last two years, I've seen a variety of duplicate issues come into the issue tracker, which stem from two fundamental flaws in Zend_Acl [...] In this article, we'll explore the API changes that alleviate these two problems, and we'll demonstrate how to leverage the Zend_Acl assertion system to create expressive, dynamic assertions that work with your applications models.

He mentions some of the backwards compatible changes that have been made to the ACL API including changes in the add() method and the ability to create Zend_Acl_Role and Zend_Acl_Resource objects explicitly. The rest of the post gives a great example of setting up users in a role, creating an action to test them against (can they work with a blog post?) and running a series of checks against the ACL component as a guest, contributor and publisher.

tagged: zendframework dynamic assertion zenacl

Link:


Trending Topics: