2

I'm new to both TDD and phpunit.

I'm testing code that forks based on it's execution method:

if (PHP_SAPI!='cli') {
    header('HTTP/1.1 '.$statusCode);
}

I want to get as much code coverage as possible, but I can't seem to test this part (because phpunit is testing via the command line interface).

Is there a way around this? Or another way to test this part?

I thought about trying to curl or something, but where the tests run will be relative to the system of the user testing it.

2
  • 2
    You actually found a code-smell. Instead you should have this as an injected parameter for that code or two implementations, one for CLI and one for HTTP so you can test both units. If this is not your code you don't need to Unit-Test it. Commented Sep 26, 2013 at 9:49
  • 1
    BTW, if you would do TDD (writing the test before writing the code), you wouldn't run into this problem in the first place. Just as an additional note and to make the TDD term a bit more clear, I'm not judging, it took me quite some time as well until I realized the benefit in writing tests first. Commented Sep 26, 2013 at 10:03

2 Answers 2

2

Abstract that comparison into its own method. Mock that method in your test to control whether or not it enters that block.

if ($this->_isCli()) {
    header('HTTP/1.1 '.$statusCode);
}

protected function _isCli() {
  return PHP_SAPI!='cli';
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using Mockery package, you cannot mock protected methods. Here is the comment of one of the developers -> Calling a mocked protected method

But you can still create a valid test if you use php_sapi_name native function

Then you can either create a dummy function with the same name in your test (inside the same namespace) to return whatever value.

or

use an extension in PHPUnit to mock static and native functions -> phpunit-mockfunction

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.