Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocking php function when global namespace specified #94

Closed
jmauerhan opened this issue Mar 19, 2016 · 3 comments
Closed

Mocking php function when global namespace specified #94

jmauerhan opened this issue Mar 19, 2016 · 3 comments

Comments

@jmauerhan
Copy link

I'm trying to test the following code (simplified here for example)

<?php
namespace Demo;

class Output{

    function sendHeader(string $header){
         \header($string);
    }
}

My test:

use AspectMock\Test as AspectMock;

public function testOutputSendsHeader()
{
    $header = AspectMock::func('', 'header', true); //I also tried first argument 'Demo'
    $output = new Demo\Output();
    $output->sendHeader('some:string);
    $header->verifyInvoked('header', 'some:string');
}

But the global header method seems to still be called, because when I run the test, I still get the PHPunit error: Cannot modify header information - headers already sent by.

@adrian-enspired
Copy link

Global functions are mocked by defining a function in the local namespace with the same name. It relies on PHP checking the local namespace before checking the global namespace (read more) — but if your code explicitly uses the root namespace (\some_function vs. some_function), PHP will not check for the local (mocked) version.

There isn't anything to do to solve this, except to change your code to not specify the global namespace when you call your functions.

@jmauerhan
Copy link
Author

Unfortunately, that wasn't an option, but thanks for the response. I've read there are some extensions that might enable creating a double for the global method, so I am going to look into those.

@loren-osborn
Copy link

How hard would it be to fake the global namespace with a mock global namespace, and adding proxy versions of all global namespace functions into all other loaded namespaces, so they can get rerouted to the mocked global namespace versions. Any explicit references would also have to be dynamically rewritten accordingly. Sounds messy, but I believe it's doable.

If you are confined to the global namespace, is there a better strategy?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants