I'm having some problems understanding mock objects.
What I want is an observer that works normally but do make sure the methods are called with the right parameters.
from what I understand so far this should be what I'm looking for: Observer:
class Observer
{
public function returnFooIfBar($bar)
{
return ($bar == 'bar') ? 'foo' : ;
}
}
Subject:
class Subject
{
$obs;
__construct(Observer $dependency)
{
$this->obs = $dependency;
}
public function tradeStrings($string)
{
$this->obs->returnFooIfBar($string);
}
}
Test:
class SubjectTest
{
public function testCallsObsMethod()
{
$obs = $this->getMock('Observer') ;
$obs->expect($this->once())
->method('returnFooIfBar')
->with($this->equlTo('bar')) ;
$subj = new Subject($obs);
$returnString= $subj->TradeStrings('bar') ;
$this->assertEqual('foo', $returnString) ;
}
}
From what I understand this tests that:
- Observer::getFooIfBar is called once.
- Observer::getFooIfBar got the string 'bar' 3.The method works as defined in the class and return 'foo' as a string.
As I understand no functionality of the original class is changed, other than the constructor / autoloading not being run.
If I mock a method when running getMock() the mocked object's method will only return something if I specify it.
$obs = $this->getMock('Observer', array('returnFooIfBar'));
$obs->expects($this->once())
->method('returnFooIfBar')
->with('bar')
->will($this->returnValue('foo');
Do I understand this right? if not could you please clarify for me as I would love some clarity on this. :)
Edit: Changed the post to make it clearer what I am after and how I currently understand it.