unit testing - Mock a public method of the class being tested -
i'm trying unit test class 1 public method (method 1) uses public method (method 2) of same class within it. e.g.
class myclass { public function method1() { $var = $this->method2(); // stuff var $answer return $answer; } public function method2() { // complex workings out $var return $var; } }
now, method2
unit tested , don't want build argument call whilst testing method1
. want mock method2
, define in test returned. have:
function test_method1() { $myclass = new myclass(); $mockedmyclass = mockery::mock('myclass'); $mockedmyclass->shouldreceive('method2')->once()->andreturn([1,2,3,4]); // mocked $var returned used in rest of method1 $answer = $myclass->method1(); // assertions }
clearly doesn't work method being tested in same class contains method being mocked, there's no way pass in mocked class dependency. what's best way mock method2?
you can use partial mock functionality of testing framework permit test same class marked mocked. example, suppose modified class:
<?php namespace acme\demobundle\model; class myclass { public function method1() { $var = $this->method2(); $answer = in_array(3, $var); // stuff var $answer return $answer; } public function method2() { // complex workings out $var return array(); } }
and tested follow:
<?php namespace acme\demobundle\tests; class myclasstest extends \phpunit_framework_testcase { function test_method1() { $mockedmyclass = \mockery::mock('acme\demobundle\model\myclass[method2]'); $mockedmyclass->shouldreceive('method2')->once()->andreturn([1,2,3,4]); // mocked $var returned used in rest of method1 $answer = $mockedmyclass->method1(); $this->asserttrue($answer); // assertions } }
hope help
Comments
Post a Comment