Unit Testing with items that need to send headers

后端 未结 11 1920
春和景丽
春和景丽 2020-12-03 01:01

I\'m currently working with PHPUnit to try and develop tests alongside what I\'m writing, however, I\'m currently working on writing the Session Manager, and am having issue

相关标签:
11条回答
  • 2020-12-03 01:15

    Can't you use output buffering before starting the test? If you buffer everything that is output, you shouldn't have problems setting any headers as no output would have yet been sent to client at that point.

    Even if OB is used somewhere inside your classes, it is stackable and OB shouldn't affect what's going on inside.

    0 讨论(0)
  • 2020-12-03 01:18

    Create a bootstrap file for phpunit, which calls:

    session_start();
    

    Then start phpunit like this:

    phpunit --bootstrap pathToBootstrap.php --anotherSwitch /your/test/path/
    

    The bootstrap file gets called before everything else, so the header hasn't been sent and everything should work fine.

    0 讨论(0)
  • 2020-12-03 01:22

    I'm wondering why nobody have listed XDebug option:

    /**
     * @runInSeparateProcess
     * @requires extension xdebug
     */
    public function testGivenHeaderIsIncludedIntoResponse()
    {
        $customHeaderName = 'foo';
        $customHeaderValue = 'bar';
    
        // Here execute the code which is supposed to set headers
        // ...
    
        $expectedHeader = $customHeaderName . ': ' . $customHeaderValue;
        $headers = xdebug_get_headers();
    
        $this->assertContains($expectedHeader, $headers);
    }
    
    0 讨论(0)
  • 2020-12-03 01:25

    I think the "right" solution is to create a very simple class (so simple it doesn't need to be tested) that's a wrapper for PHP's session-related functions, and use it instead of calling session_start(), etc. directly.

    In the test pass mock object instead of a real stateful, untestable session class.

    private function __construct(SessionWrapper $wrapper)
    {
       if (!$wrapper->headers_sent())
       {
          $wrapper->session_start();
          $this->session_id = $wrapper->session_id();
       }
    }
    
    0 讨论(0)
  • 2020-12-03 01:28

    It seems that you need to inject the session so that you can test your code. The best option I have used is Aura.Auth for the authentication process and using NullSession and NullSegment for testing.

    Aura testing with null sessions

    The Aura framework is beautifully written and you can use Aura.Auth on its own without any other Aura framework dependencies.

    0 讨论(0)
提交回复
热议问题