14

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.

  • Exactly this. Check whether your event is dispatched and then just call the observer method with mock data and check it is correct. Ideally you should check that the observer is configured for the correct event – Fabian Blechschmidt Dec 3 '13 at 17:42
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.