0

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

Ben
  • 25,389
  • 34
  • 109
  • 165

2 Answers2

4

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

Distdev
  • 2,312
  • 16
  • 23
  • 1. also protected method should tested 2.__construct is public method – Ben Feb 08 '11 at 13:56
  • [the same method for ReflectionMethod](http://php.net/manual/en/reflectionmethod.setaccessible.php) – Distdev Feb 08 '11 at 14:00
  • Also you can read [article from author of PHPUnit](http://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html) – Distdev Feb 08 '11 at 14:01
0

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

Oswald
  • 31,254
  • 3
  • 43
  • 68