<?php | |
require 'PHPUnit/Framework/TestCase.php'; | |
class CouchDB | |
{ | |
public function doGeloet() | |
{ | |
return $this->makeRequest(); | |
} | |
protected function makeRequest() | |
{ | |
return 'doing external shit'; | |
} | |
} | |
class CouchDBTest extends PHPUnit_Framework_TestCase | |
{ | |
public function testYourMum() | |
{ | |
$couch = $this->getMock('CouchDB', array('makeRequest')); | |
$couch->expects($this->any())->method('makeRequest')->will($this->returnValue('Stubbed!')); | |
$this->assertEquals('Stubbed!', $couch->doGeloet()); | |
} | |
} |
For some reason, even if I add array('makeRequest')
, everything else is stubbed too.
So I need to configure an expectation for everything -- kinda defeats the purpose.
Btw, nice test name.
Hrhr ;)
Here's an example that is closer to your example code:
<?php
require 'PHPUnit/Framework/TestCase.php';
class CouchDB
{
public function getDocument($id)
{
$uri = 'http://server:5984/db/' . $id;
$response = $this->makeRequest($uri);
return $this->parseResponse($response);
}
protected function makeRequest($uri)
{
return my_super_duper_client($uri);
}
/**
* @param string $response Most likely JSON.
*
* @return stdClass
* @throws RuntimeException On 404.
*/
protected function parseResponse($response)
{
$obj = json_decode($response);
if (isset($obj->error)) {
throw new RuntimeException("Not found: {$obj->reason}", 404);
}
return $obj;
}
}
class CouchDBTest extends PHPUnit_Framework_TestCase
{
public function testYourMum()
{
$couch = $this->getMock('CouchDB', array('makeRequest'));
$couch
->expects($this->any())
->method('makeRequest')
->will($this->returnValue(json_encode(array('blub')))
);
$this->assertEquals(array('blub'), $couch->getDocument(3));
}
}
Now you can set the stubbed server response with will($this->returnValue(json_encode(array('blub')))
Hth!
For some reason, even if I add array('makeRequest'), everything else is stubbed too.
So I need to configure an expectation for everything -- kinda defeats the purpose.
Yeah that's strange and not intended. Btw i use phpunit 3.5.14.
If it still does not work, please post your updated code. I think we're getting closer ;)
Yeah, working now. I probably didn't have getMock('foo', array('protectedMethod')). That's the only thing I can think of. Though I'm sure I tried that before. ;-(
Thanks!
I can't get that to work for some reason.
My
$this->returnValue()
is slightly different:It could be that I need to define an expectation for
parseResponse()
andgetDocument()
too. A fake did the trick though.