Unit Testing with items that need to send headers

后端 未结 11 1938
春和景丽
春和景丽 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:07

    As I'm unittesting my bootstrap right now (yes I know most of you don't do that), I'm running in to the same problem (both header() and session_start()). The solution I found is rather simple, in your unittest bootstrap define a constant and simply check it before sending the header or starting the session:

    // phpunit_bootstrap.php
    define('UNITTEST_RUNNING', true);
    
    // bootstrap.php (application bootstrap)
    defined('UNITTEST_RUNNING') || define('UNITTEST_RUNNING', false);
    .....
    if(UNITTEST_RUNNING===false){
        session_start();
    }
    

    I agree that this is not perfect by design, but I'm unittesting an existing application, rewriting large parts is not desired. I also using the same logic to test private methods using the __call() and __set() magic methods.

    public function __set($name, $value){
        if(UNITTEST_RUNNING===true){
           $name='_' . $name;
           $this->$name=$value;
        }
        throw new Exception('__set() can only be used when unittesting!');
     }
    

提交回复
热议问题