I am new to phpunit and have read the documentation on mock objects, but this is not very clear.
I am trying to write a simple test that claims a method inside a class. In the following code, I verify that when calling Client :: exchangeArray, a call to Client :: getInputFilter is made.
class Client implements InputFilterAwareInterface { public function getInputFilter() { if(!$this->_inputFilter){ $inputFactory = new InputFactory(); $inputFilter = new InputFilter(); $inputFilter->add($inputFactory->createInput(array( 'name' => 'id', 'required' => true, 'filters' => array( array( 'name' => 'Int' ) ) ))); $inputFilter->add($inputFactory->createInput(array( 'name' => 'name', 'required' => true, 'filters' => array( array( 'name' => 'StripTags' ), array( 'name' => 'StringTrim' ), array( 'name' => 'StripNewLines' ), array( 'name' => 'Alpha' ) ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 2, 'max' => 100 ) ) ) ))); $inputFilter->add($inputFactory->createInput(array( 'name' => 'surname', 'required' => true, 'filters' => array( array( 'name' => 'StripTags' ), array( 'name' => 'StringTrim' ) ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 2, 'max' => 100 ) ) ) ))); $inputFilter->add($inputFactory->createInput(array( 'name' => 'email', 'required' => false, 'filters' => array( array( 'name' => 'StripTags' ), array( 'name' => 'StringTrim' ) ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 2, 'max' => 150 ) ), array( 'name' => 'EmailAddress' ) ) ))); $this->_inputFilter = $inputFilter; } return $this->_inputFilter; } public function exchangeArray($data){ $inputFilter = $this->getInputFilter(); $inputFilter->setData($data); if(!$inputFilter->isValid()){ throw new \Exception('Invalid client data'); } $cleanValues = $inputFilter->getValues(); $this->_id = (isset($cleanValues['id']) ? $cleanValues['id'] : null); $this->_name = (isset($cleanValues['name']) ? $cleanValues['name'] : null); $this->_surname = (isset($cleanValues['surname']) ? $cleanValues['surname'] : null); $this->_email = (isset($cleanValues['email']) ? $cleanValues['email'] : null); } }
Here is my test case:
public function testExchangeArrayCallsInputFilter(){ $data = array('id' => 54, 'name' => 'john', 'surname' => 'doe', 'email' => ' john.doe@domain.com ' ); $mock = $this->getMock('Client', array('exchangeArray')); $mock->expects($this->once()) ->method('getInputFilter'); $mock->exchangeArray($data); }
... and I get the following error:
The wait error for the method name is equal when called 1 time (s). The method should have been called 1 time, actually called 0 times.
Where am I mistaken?