| Server IP : 127.0.1.1 / Your IP : 216.73.216.152 Web Server : Apache/2.4.52 (Ubuntu) System : Linux bahcrestlinepropertiesllc 5.15.0-113-generic #123-Ubuntu SMP Mon Jun 10 08:16:17 UTC 2024 x86_64 User : www-data ( 33) PHP Version : 7.4.33 Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare, MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/bahcrestline/core/vendor/mockery/mockery/docs/getting_started/ |
Upload File : |
.. index::
single: Getting Started; Simple Example
Simple Example
==============
Imagine we have a ``Temperature`` class which samples the temperature of a
locale before reporting an average temperature. The data could come from a web
service or any other data source, but we do not have such a class at present.
We can, however, assume some basic interactions with such a class based on its
interaction with the ``Temperature`` class:
.. code-block:: php
class Temperature
{
private $service;
public function __construct($service)
{
$this->service = $service;
}
public function average()
{
$total = 0;
for ($i=0; $i<3; $i++) {
$total += $this->service->readTemp();
}
return $total/3;
}
}
Even without an actual service class, we can see how we expect it to operate.
When writing a test for the ``Temperature`` class, we can now substitute a
mock object for the real service which allows us to test the behaviour of the
``Temperature`` class without actually needing a concrete service instance.
.. code-block:: php
use \Mockery;
class TemperatureTest extends \PHPUnit\Framework\TestCase
{
public function tearDown()
{
Mockery::close();
}
public function testGetsAverageTemperatureFromThreeServiceReadings()
{
$service = Mockery::mock('service');
$service->shouldReceive('readTemp')
->times(3)
->andReturn(10, 12, 14);
$temperature = new Temperature($service);
$this->assertEquals(12, $temperature->average());
}
}
We create a mock object which our ``Temperature`` class will use and set some
expectations for that mock — that it should receive three calls to the ``readTemp``
method, and these calls will return 10, 12, and 14 as results.
.. note::
PHPUnit integration can remove the need for a ``tearDown()`` method. See
":doc:`/reference/phpunit_integration`" for more information.