php - phpunit testing method that calls other class methods which need mock -


i'm trying create pretty standard unit test call method , assert it's response, method i'm testing calls method inside same class little bit of heavy lifting.

i want mock 1 method still execute method i'm testing is, mocked value returned call other method.

i've dumbed down example make simple possible.

class myclass {      // want test method, mock handlevalue method return set value.      public function testmethod($arg)     {          $value = $arg->getvalue();          $this->handlevalue($value);      }       // method needs mocked return set value.      public function handlevalue($value)     {          // bunch of stuff...         $value += 20;          return $value;      }  } 

my attempt @ writing tests.

class myclasstest extends \phpunit_framework_testcase {       public function testthetestmethod()     {          // mock object passed in arg         $arg = $this->getmockbuilder('someentity')->getmock();         $arg->expects($this->any())             ->method('getvalue')             ->will($this->returnvalue(10));          // test handle document()         $myclass = new myclass();          $result = $myclass->testmethod($arg);          // assert result correct         $this->assertequals($result, 50);      }  } 

i have tried mocking myclass object, when , call testmethod returns null. need way mock 1 method leave rest of object intact.

you can mock class testing , specify method want mock.

$mock = $this->getmockbuilder('myclass')     ->setmethods(array('handlevalue'))     ->getmock();  $mock->expects($this->once())     ->method('handlevalue')     ->will($this->returnvalue(23)) //whatever value want return 

however, imo not best idea tests. testing make refactoring more difficult. specifying implementation of class rather behavior class supposed have. if handlevalue doing lot of complicated work makes testing difficult, consider moving logic separate class , injecting class. can create mock of class , pass in testmethod. doing give added advantage of making myclass more extensible if handlevalue needs adapt behavior.

http://www.oodesign.com/strategy-pattern.html

as general rule, should not mock system testing.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -