First steps mocking with PHPUnit

Our class:

class CanviPool
{
    public function retValue($val)
    {
        return $val;
    }
}

Our mocking class:

class CanviPoolTest extends TestBase
{
public function test_UT_ReturnValue()
{
// A mock object is created using CanviPool class
// The method 'retValue' will be mocked
$conConfig = $this->getMock('CanviPool', array('retValue'));

// We expect to use 'retValue' method ANY times in this test
// The mocked method is 'retValue'
// The mocked method will return the value 3
$conConfig
->expects($this->any())
->method('retValue')
->will($this->returnValue(3));

// We call the mocked method passing the required parameter
$res = $conConfig->retValue(1);
// Wen we compare the result with the value 3, the assert is true
$this->assertEquals(3, $res);

// We can do a new test
$res = $conConfig->retValue(1);
// And the result will be 3 again, because of the parameter ANY "->expects($this->any())"
// if insted of "any" the word was "once" this test would fail
$this->assertEquals(3, $res);
}
}

	

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *