How to test an action's output in ZF2/ZF3?

290 views Asked by At

How to catch the (ViewModel) output of a controller action in ZF2/ZF3?

Background:

I'm writing some integration tests for a Zend Framework 3 application (just migrated from ZF2). I'm using PHPUnit v6.2.2 and Zend\Test v3.1.0. I want to test the part of the process from the moment, when the route is called, to the moment, when the data is saved/retrieved. That means testing of all controller actions in to directions:

  1. the data gets saved as expected (for this I want to call the routes/actions and check then the new database state);
  2. the data gets retrieved as expected (for this I want to call the routes/actions and check then the action's output).

The first direction is clear: After calling the route, I simply start plain database requests and check, if the expected changes are there.

public function testBuzAction()
{
    $this->dispatch('/foo/bar/buz');
    // Here might be optionally some asserts, whether the correct action is called...
    // Here are the database checks...
}

But for the other direction we need the ViewModel, returned by the action.

public function testBuzAction()
{
    $this->dispatch('/foo/bar/buz');
    // Here might be optionally some asserts, whether the correct action is called...
    // Here is the ViewModel output of the Bar#buzAction() analyzed.
}

How to get the action's output wothin a PHPUnit test?

1

There are 1 answers

0
automatix On BEST ANSWER
public function testBuzAction()
{
    $this->dispatch('/foo/bar/buz');
    ...
    $viewModelReturnedByAction = $this->getApplication()->getMvcEvent()->getResult();
}