Create a mock class
You want to:
Create a stand-in mock object to decouple your testable unit from its surroundings.
Quite often, a particular class will require collaborators to accomplish its purpose in production code. For testing, however, you want to decouple the system under test from its collaborators, so that you can limit unintentional side-effects. Mock objects serve as stand-in collaborators that allow for that decoupling.
Solution:
Use $this->getMock() and its fluent interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
require_once "PHPUnit/Framework.php";
class FilesMultiplier
{
/*
* Read a pair of numbers from a file, mutiply, and return.
*/
public function multiply($inputFile)
{
$line = $inputFile->read();
$parts = explode(" ", $line);
$a = (integer) $parts[0];
$b = (integer) $parts[1];
$result = ($a * $b);
return $result;
}
}
class FileObject
{
/*
* This function reads a line from a file.
*/
public function read()
{
// ... code omitted
}
}
class TestFilesMultiplier extends PHPUnit_Framework_TestCase
{
public function test_multiply()
{
$multiplier = new FilesMultiplier();
$inputFile = $this->getMock('FileObject',
array('read'));
$inputFile->expects($this->once())
->method('read')
->will($this->returnValue("3 4"));
$result = $multiplier->multiply($inputFile);
$this->assertEquals($result, 12,
"Multiplying 3 by 4 did not give 12 as expected.");
}
}
?>
