I have an if condition inside an observer as follows

public function execute(Observer $observer)
        if ($observer->getData('status') == Status::REQUIRED) {

Now I want to write a PHPUnit test for above.

How can I do so? basically, I want to know how can I bypass the if a condition or set it to true in my unit test.


//implementation looks something like below

if ($observer->getData('var_first') == 'var_first_value') {
            $data = $observer->getData('var2')->getData();

I think in you can mock your Observer class with getData method


$eventObserverMock = $this->getMockBuilder(Observer::class)

Now getData method is mock so you can set the some value with return type which you want true or false

        ->willReturn('some value'); // here you can set your value which you want and use `$eventObserverMock` while calling your `execute` method




If you have multiple parameters then you can pass with comma separated like ->with($some,$demo) and If you don't care about your parameter or you have lots of parameters then you can write like ->withAnyParameters()

And for multiple calling, you can play it here ->expects($this->any()) with $this->exactly(1) here you need to replace 1 with your calling method count

  • What if there are multiple calling of getData() with different params? – Anshu Mishra May 17 '19 at 11:41
  • Please see my edit.. @AnshuMishra – Keyur Shah May 17 '19 at 11:47
  • Then how will I manage the return value because based on the parameter return value is changing. – Anshu Mishra May 17 '19 at 11:52
  • Means what will I put inside the ->willReturn() – Anshu Mishra May 17 '19 at 11:52
  • you can put any value which you want like "test" or "demo" or anything @AnshuMishra – Keyur Shah May 17 '19 at 11:55

I have used following code to make the test work

    $this->observerMock = $this->getMockBuilder(Observer::class)


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.