Magento – Unit Testing Observers in Magento

ecomdev-phpunitunit tests

How do you approach unit testing Observers in Magento? (working with EcomDev_PHPUnit)

What kind of assertions do include?

  • check if the event is being dispatched (assertEventDispatched())
  • check the function with mock data

Ideally I would like to see other developers opinion regarding the approach and assertions made.

Best Answer

I also like to ensure that the observer is in fact called when doing an appropriate action, e.g. when you dispatch a catalog_product_save_after, then do something like:

// initialize $mock as your observer
$mock->expects($this->once())
     ->method('catalogProductSaveAfter')
     ->will($this->returnSelf()); // the observer usually returns itself
$product = Mage::getModel('catalog/product')->load(4);
// Do action which should dispatch your event once
$product->setName("test")->save();

This will fail if your method is not called exactly once.

Related Topic