php - Code coverage when not testing protected/private methods with PHPUnit -


i know it's possible test private/protected methods phpunit using reflection or other workarounds.

but sources tell me it's not best practice write tests private methods inside of class.

you supposed test class if "black box" — test expected behavior comparing inputs outputs disregarding internal mechanics. writing tests classes should notify unused private methods, showing lack of code coverage.

when test class , generate html report, shows private methods not covered tests, though lines called absolutely executed/covered. know private methods executed, because if weren't assertions on class not pass.

is expected behavior in phpunit? can strive 100% coverage, while still testing private methods indirectly?

some simplified example code (using restbundle in symfony2):

class apicontroller extends fosrestcontroller {  /*  * @rest\view()  * @rest\get("/api/{codes}")  */ public function getcodesaction($codes) {     $view = new view();     $view->setheader('access-control-allow-origin', '*');     $view->setdata(array('type' => 'codes','data' => $this->_stringtoarray($codes)));     $view->setformat('json')->setheader('content-type', 'application/json');     return $this->handleview($view); }  private function _stringtoarray($string){     return explode('+',$string); } 

the public function shows "covered", private function indirectly covered shows colored red in phpunit reports.

test:

class apicontrollertest extends webtestcase {      public function test_getcodesaction(){         $client = static::createclient();         $client->request('get', '/api/1+2+3');         $this->assertcontains('{"type": "codes", "data": [1,2,3]}', $client->getresponse()->getcontent());     }  } 

this silly example of course, include explode() right there in public function; controllers i'm writing tests contain more intricate , re-usable private functions transform data in more complex ways (but still side-effect free).

in phpunit can specify covered methods special annotation, descrived in doc.

you can this:

    class apicontrollertest extends webtestcase {          /**          * @covers apicontroller::getcodesaction          * @covers apicontroller::_stringtoarray          */         public function test_getcodesaction(){             $client = static::createclient();             $client->request('get', '/api/1+2+3');             $this->assertcontains('{"type": "codes", "data": [1,2,3]}', $client->getresponse()->getcontent());         }      } 

hope help


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -