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

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

1. also protected method should tested 2.__construct is public method
0

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

1 Comment

this option should exist in phpunit if not this should be added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.