PHP: Mock header() to Unit Test Controllers

In 2011 I suggested a technique to mock functions in PHP Unit Tests that takes advantage of the name resolution rules of PHP namespaces. You can read it here:

It makes me proud that the great Matthew Weier O’Phinney 1 now describes the same technique to test code that emits output, especially code that sends headers with the built-in header() function. Read more in his post here:

In my opinion this is a great example of how useful this method is. “Headers already sent” errors in your unit tests can drive you crazy. Unfortunately, there are still many applications that do not use namespaces (*cough* Magento *cough*) where it does not work.

Notes:

  1. for those who don’t know him: He’s the Zend Framework Project Lead and you should follow his blog at http://mwop.net/blog.html!

Magento Testing: Fill Forms with one click

Who doesn’t know this situation: When testing features like the guest checkout manually, you have to fill all form fields tedously again and again. With Chrome auto complete or “test”, Ctrl + C, Ctrl + V it’s halfway fast but still a bit annoying. And what if the test data is supposed to make sense and should not be the same every time?

Inspired by this article on css-tricks.com I developed a little Magento module, that enables filling Magento forms with dummy data with one mouse click. Currently it is implemented for billing address and shipping address.

Github-Repository: SSE_FormFiller

And this is how it looks:

Screenshot: Forms in Checkout

Configuration

Of course you want to see this button only on your development system, that’s why there are two ways to hide it: Either disable the module completely per configuration or show the button only in developer mode:

SSE_FormFiller Configuration

The nice thing about the second variation is that the JavaScript still gets loaded, so that you can substitute the button with a bookmarklet. Here the snippets:

Billing address form

JavaScript:

formFiller.fill(billingForm.form)

Bookmarklet (right click, add as bookmark!)

Shipping address form

JavaScript:

formFiller.fill(shippingForm.form)

Bookmarklet (right click, add as bookmark!)

Technology

A bit of information on the implementation:

  • The dummy data comes from Faker.js.
  • The button gets added to choosen blocks with an observer for core_block_abstract_to_html_after
  • In the JavaScript the form ID determines which fields should be filled.

The module is designed to be extended for other forms as well. Suggestions and of course pull requests on Github are most welcome! Continue reading “Magento Testing: Fill Forms with one click”