I'm currently developing a simple framework for PHP that manages and dispatches ajax calls. One of its features is that it automatically takes care of sending the appropriate headers depending on what is happening in the backend. During the past couple of days I've started writing a lot of unit tests for PHPUnit and I'm trying to get a decent code coverage. (Yes, high code coverage by itself doesn't really mean anything, I know. But it still is a good indicator.)
However, because it is (to my knowledge) not possible to send/check headers when PHP is in CLI mode, a lot of tests need to be run through a local webserver. This allows me to easily check the headers and the response body. Unfortunately, the code executed during these tests is, naturally, not tracked by PHPUnit. (Just to be clear: every piece of c开发者_高级运维ode that can be checked locally, is checked locally. But everything that is related to headers does not fall into that category.)
I know that I can encapsulate the header()
call and replace it during testing with a mock object. However, then I'd have to re-implement the entire logic of header replacement and what not with all its potential quirks and bugs, so I'd essentially be testing my own header()
-implementation instead of what's really happening - which is precisely what I don't want to do.
So I guess my question is this: can I, somehow, include those "remote calls" in my code coverage report? Or do I (and that's my guess) simply have to accept the fact that I've to miss out on 100% code coverage in order to test under real-world conditions?
Well, in practice it's practically impossible to get 100% coverage for an entire code base. Where you really want 100% is in the core of the application (The libraries and reused components). The rest is very good to test, but if you'll find there are situations that make it quite difficult to test, so don't stress yourself over a few lines of code that are untestable.
As far as your specific problem, I wouldn't even be writing unit tests for that sort of thing. What I would write are UI tests using Selenium HQ. It's still fully automated, and runs from within PHPUnit, but it uses one or more browsers. It's really more of an integration or acceptance test than a Unit test, but it works quite well...
Apparently, there is no way to do it.
While ircmaxell's answer was interesting, it didn't really answer my question (hence I marked this answer as accepted).
精彩评论