1
+ <?php
2
+ namespace TDD \Test ;
3
+ require dirname ( dirname (__FILE__ ) ) . DIRECTORY_SEPARATOR . 'vendor ' . DIRECTORY_SEPARATOR . 'autoload.php ' ;
4
+
5
+ use PHPUnit \Framework \TestCase ;
6
+ use TDD \ItemsTable ;
7
+ use \PDO ;
8
+
9
+ class ItemsTableTest extends TestCase
10
+ {
11
+
12
+ public function setUp ()
13
+ {
14
+ $ this ->PDO = $ this ->getConnection ();
15
+ $ this ->createTable ();
16
+ $ this ->populateTable ();
17
+
18
+ $ this ->ItemsTable = new ItemsTable ($ this ->PDO );
19
+ }
20
+
21
+ public function tearDown ()
22
+ {
23
+ unset($ this ->ItemsTable );
24
+ unset($ this ->PDO );
25
+ }
26
+
27
+ public function testFindForId ()
28
+ {
29
+ $ id = 1 ;
30
+
31
+ $ result = $ this ->ItemsTable ->findForId ($ id );
32
+ $ this ->assertInternalType (
33
+ 'array ' ,
34
+ $ result ,
35
+ 'The result should always be an array. '
36
+ );
37
+ $ this ->assertEquals (
38
+ $ id ,
39
+ $ result ['id ' ],
40
+ 'The id key/value of the result for id should be equal to the id. '
41
+ );
42
+ $ this ->assertEquals (
43
+ 'Candy ' ,
44
+ $ result ['name ' ],
45
+ 'The id key/value of the result for name should be equal to `Candy`. '
46
+ );
47
+ }
48
+
49
+ public function testFindForIdMock ()
50
+ {
51
+ $ id = 1 ;
52
+
53
+ $ PDOStatement = $ this ->getMockBuilder ('\PDOStatement ' )
54
+ ->setMethods (['execute ' , 'fetch ' ])
55
+ ->getMock ();
56
+
57
+ $ PDOStatement ->expects ($ this ->once ())
58
+ ->method ('execute ' )
59
+ ->with ([$ id ])
60
+ ->will ($ this ->returnSelf ());
61
+ $ PDOStatement ->expects ($ this ->once ())
62
+ ->method ('fetch ' )
63
+ ->with ($ this ->anything ())
64
+ ->will ($ this ->returnValue ('canary ' ));
65
+
66
+ $ PDO = $ this ->getMockBuilder ('\PDO ' )
67
+ ->setMethods (['prepare ' ])
68
+ ->disableOriginalConstructor ()
69
+ ->getMock ();
70
+
71
+ $ PDO ->expects ($ this ->once ())
72
+ ->method ('prepare ' )
73
+ ->with ($ this ->stringContains ('SELECT * FROM ' ))
74
+ ->willReturn ($ PDOStatement );
75
+
76
+ $ ItemsTable = new ItemsTable ($ PDO );
77
+
78
+ $ output = $ ItemsTable ->findForId ($ id );
79
+
80
+ $ this ->assertEquals (
81
+ 'canary ' ,
82
+ $ output ,
83
+ 'The output for the mocked instance of the PDO and PDOStatment should produce the string `canary`. '
84
+ );
85
+ }
86
+
87
+ protected function getConnection ()
88
+ {
89
+ return new PDO ('sqlite::memory: ' );
90
+ }
91
+
92
+ protected function createTable ()
93
+ {
94
+ $ query = "
95
+ CREATE TABLE `items` (
96
+ `id` INTEGER,
97
+ `name` TEXT,
98
+ `price` REAL,
99
+ PRIMARY KEY(`id`)
100
+ );
101
+ " ;
102
+ $ this ->PDO ->query ($ query );
103
+ }
104
+
105
+ protected function populateTable ()
106
+ {
107
+ $ query = "
108
+ INSERT INTO `items` VALUES (1,'Candy',1.00);
109
+ INSERT INTO `items` VALUES (2,'TShirt',5.34);
110
+ " ;
111
+ $ this ->PDO ->query ($ query );
112
+ }
113
+ }
0 commit comments