PHPUnit::How can be __construct with protected variables tested?

1.4k views Asked by At

PhpUnit::How can be __construct with protected variables tested?

(not always we should add public method getVal()- soo without add method that return protected variable value)

Example:

  class Example{
    protected $_val=null;
    function __construct($val){
      $this->_val=md5 ($val);
    }
   }

Edit:

also exist problem to test in function that return void


Edit2:

Example why we need test __construct:

class Example{
        protected $_val=null;
       //user write _constract instead __construct
        function _constract($val){
          $this->_val=md5 ($val);
        }

       function getLen($value){
         return strlen($value);
       }
 }

 class ExampleTest extends PHPUnit_Framework_TestCase{
     test_getLen(){
       $ob=new Example();//call to __construct and not to _constract
        $this->assertEquals( $ob->getLen('1234'), 4);
     }
 }

test run ok, but Example class "constructor" wasn't created!

Thanks

2

There are 2 answers

3
Distdev On BEST ANSWER

The main goal of unit testing is to test interface By default, you should test only public methods and their behaviour. If it's ok, then your class is OK for external using. But sometimes you need to test protected/private members - then you can use Reflection and setAccessible() method

1
Oswald On

Create a derived class that exposes the value that you want to test.