Returning a mock object from a mock object

Posted by Songo on Programmers See other posts from Programmers or by Songo
Published on 2012-10-14T13:43:41Z Indexed on 2012/10/14 15:49 UTC
Read the original article Hit count: 445

I'm trying to return an object when mocking a parser class. This is the test code using PHPUnit 3.7

    //set up the result object that I want to be returned from the call to parse method
    $parserResult= new ParserResult();
    $parserResult->setSegment('some string');        

    //set up the stub Parser object
    $stubParser=$this->getMock('Parser');
    $stubParser->expects($this->any())
               ->method('parse')
               ->will($this->returnValue($parserResult));

    //injecting the stub to my client class
    $fileHeaderParser= new FileWriter($stubParser);
    $output=$fileParser->writeStringToFile();

Inside my writeStringToFile() method I'm using $parserResult like this:

writeStringToFile(){
   //Some code...
    $parserResult=$parser->parse();
    $segment=$parserResult->getSegment();//that's why I set the segment in the test.
}

Should I mock ParserResult in the first place, so that the mock returns a mock? Is it good design for mocks to return mocks?

Is there a better approach to do this all?!

© Programmers or respective owner

Related posts about design

Related posts about programming-practices