Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

You can test symfony event listener with a simple test as shown below.


EventListener


namespace My\ProductBundle\EventListener;

use Doctrine\ORM\Event\PreUpdateEventArgs;
use My\ProductBundle\Entity\Product;

class ProductEventListener
{
/**
* @param PreUpdateEventArgs $event
*/
public function preUpdate(PreUpdateEventArgs $event)
{
$entity = $event->getObject();
if ($entity instanceof Product) {
if ($event->hasChangedField('price')) {
if ($event->getOldValue('price') != $event->getNewValue('price')) {
$this->capturePriceChange($entity, $event->getNewValue('price'));
}
}
}
}

/**
* @param string $newPrice
* @param Product $product
*/
private function capturePriceChange(Product $product, $newPrice)
{
// Do something with $price and $newPrice here
}
}

EventListener Test


namespace spec\My\ProductBundle\EventListener;

use Doctrine\ORM\Event\PreUpdateEventArgs;
use My\ProductBundle\Entity\Product;
use PhpSpec\ObjectBehavior;

class ProductEventListenerSpec extends ObjectBehavior
{
function it_should_not_capture_price_change_in_the_case_of_no_change_on_pre_update_event(
PreUpdateEventArgs $event,
Product $product
) {
$old = 123;
$new = 123;
$hasPriceChanged = false;

$event->getObject()->shouldBeCalled()->willReturn($product);
$event->hasChangedField("price")->shouldBeCalled()->willReturn($hasPriceChanged);
$event->getOldValue("price")->shouldNotBeCalled()->willReturn($old);
$event->getNewValue("price")->shouldNotBeCalled()->willReturn($new);

// Do the same thing with $additionalData and $newPrice here as done in the listener
// You can use shouldBeCalled() and willReturn(...) or shouldNotBeCalled()

$this->preUpdate($event);
}

function it_should_capture_price_change_in_the_case_of_change_on_pre_update_event(
PreUpdateEventArgs $event,
Product $product
) {
$old = 123;
$new = 321;
$hasPriceChanged = true;

$event->getObject()->shouldBeCalled()->willReturn($product);
$event->hasChangedField("price")->shouldBeCalled()->willReturn($hasPriceChanged);
$event->getOldValue("price")->shouldBeCalled()->willReturn($old);
$event->getNewValue("price")->shouldBeCalled()->willReturn($new);

// Do the same thing with $additionalData and $newPrice here as done in the listener
// You can use shouldBeCalled() and willReturn(...) or shouldNotBeCalled()

$this->preUpdate($event);
}
}