headers exception with Zend_Session while unit testing

While the manual for Zend_Session does discuss unit testing and the read-only exception, it has no mention of an exception I encountered recently while unit testing. I admit that the reason I encountered the exception is most likely because I’m Doing It Wrong. However, given reality, I did not have time to properly make the class, or at least do it better. I received the following exception:

exception ‘Zend_Session_Exception’ with message ‘Session must be started before any output has been sent to the browser; output started…’

The problem was, of course, that the feedback from previous tests was already outputted to the screen. I could’ve solved this by playing with my test suite and just starting sessions at that level but that wouldn’t have been the best solution. In fact, I’d qualify that solution under bandaids (solutions that mask a problem instead of fixing them). If you can’t see why it is a bandaid, I’m happy to discuss it but for once, I”m going to try to stay on topic and not digress any further than I have.

So, here’s the scenario:

  • not enough time to refactor the class so that sessions are only called/created when necessary
  • sessions are being called because we’re testing some auth stuff which relies on session information, we might not be able to do DI (see above)
  • we want to minimize contributing factors to test failure so session has to be called/destroyed for the tests that need it, all other tests should never have session existing

The solution? A little ‘undocumented’ static variable:

Zend_Session::$_unitTestEnabled = true;

Ok, undocumented is a bit misleading. You won’t find out about it by looking at the Manual but will find it when you’re digging through the API. So it is documented, just not well. I’m guessing because it is rare to encounter the exception. I’m not surprised that I encountered it since my projects always seem to have some degree of weirdness, which makes for an interesting learning curve thats compounded with Zend’s curve.

1 comment on “headers exception with Zend_Session while unit testingAdd yours →

  1. I've found this answer in a few places however, I still don't seem to know where to add Zend_Session::$_unitTestEnabled = true;

    ?

Leave a Reply