php - phpunit runs test twice - gets two answers. Why? -


this phpunit test file

<?php // demotest - test prove point  function __autoload($classname) {     //  pick file current directory     $f = $classname.'.php';      require_once $f; }  class demotest extends phpunit_framework_testcase {     // call same test twice - det different results      function test01() {         $this->controller = new demo();         ob_start();         $this->controller->handleit();         $result = ob_get_clean();           $expect = 'actions array';         $this->assertequals($expect,$result);     }      function test02() {         $this->test01();     } } ?> 

this file under test

<?php // demo.php global $actions; $actions=array('one','two','three'); class demo {     function handleit() {         global $actions;         if (is_null($actions)) {             print "actions null";         } else {             print('actions array');         }     } } ?> 

the result second test fails because $actions null.

my question - why don't same results 2 tests?

is bug in phpunit or understanding of php?

phpunit has feature called "backup globals", if turned on, @ beginning of test variables in global scope backed (a snapshot made of current values) , after each test completed, values restored again original values. can read more here: http://sebastian-bergmann.de/archives/797-global-variables-and-phpunit.html#content

now lets @ test suite.

  1. test01 prepared
  2. backup made of global variables (at point $actions in global scope not set, because code has not ran yet)
  3. test01 runs
  4. demo.php included (thanks autoload) , $actions set in global scope
  5. your assertion succeeds, because $actions set in global scope
  6. test01 torn down. global variables returned original value. $actions in global scope destroyed @ point, because set inside test, not part of global state before start of test
  7. test02 runs .. , fails, because there no $actions in global scope.

direct fix problem: include demo.php @ beginning of demotest.php, way $actions ends in global scope backed , restored before , after every test.

long term fix: try avoid use of globals. bad habit , there better solutions global state using 'global'.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -