EcomDev PHPUnit Tip #14

For years, the test framework EcomDev_PHPUnit is quasi-standard for Magento unit tests. The current version is 0.3.7 and last state of official documentation is version 0.2.0 – since then, much has changed which you have to search yourself in code and GitHub issues. This series shall collect practical usage tips.

Tip #14: Registry Fixtures

As already explained in Tip #1, helpers, singletons and registry values can be reset per test. Finding the problematic singletons etc. often was the most difficult part of writing integration tests with EcomDev, so I started to collect them centralized in one fixtures/registry.yaml file for all tests 1. Better reset one too many than one to little.

The file is structured like this:

    - product
    - current_product
    - current_category
    - current_entity_key
    - catalogsearch
    - catalog/layer
    - core/session
    - customer/session
    - catalog/session
    - customer/session
    - reports/session
    - catalog/category_indexer_product

But caution!

As soon as one test uses one of the annotations @registry, @helper, @singleton or @resource, the entries of the YAML file are overwritten. Using both together does not work!

Devious Singletons

Some not quite obvious singletons that can lead to frustration, are:

  • customer/session – as soon as you work with product collections, a customer session is instantiated automatically (because of group prices). In this case, it’s the best in my experience to inherit your test from EcomDev_PHPUnit_Test_Case_Controller and start the customer session like this:

    Additionally, customer/session belongs on the list of singletons to reset, just like all other session models.

  • catalog/category_indexer_producty (Resource Singleton) – I stumbled over this just today: If the tests run on a virgin database and the Magento setup scripts are triggered in the same process, this singleton saves the stores before the default store even exists. As soon as the indexer is triggered but cannot find any stores, you’ll see this helpful error message:

    Fatal error: Uncaught exception 'Exception' with message 'Notice: Undefined variable: enabledTable in /var/www/app/code/core/Mage/Catalog/Model/Resource/Category/Indexer/Product.php on line 941

    That’s why this singleton should always be resetted and the registry fixture that takes care about this should be loaded bevore any EAV fixture