-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtdd-cheatsheet.tex
789 lines (589 loc) · 24 KB
/
tdd-cheatsheet.tex
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
\documentclass[a4paper,11pt,headsepline]{scrartcl}
\include{packages}
\include{styles}
\usepackage[american]{babel}
\selectlanguage{american}
\bibliographystyle{alpha}
\hypersetup{
pdfauthor={Oliver Klee, [email protected], @oliklee},
pdftitle={Test-driven development with PHPUnit (with and without TYPO3)},
pdfsubject={Handout for Oliver Klee's workshops on test-driven development with PHPUnit (with and without TYPO3).},
pdfkeywords={TDD, unit testing, PHPUnit, workshop, seminar, PHP}
}
\author{
Oliver Klee | \texttt{[email protected]} | \texttt{@oliklee} \\
\url{https://github.com/oliverklee/tdd-reader}
}
\date{Version 3.1.0, \today, for TYPO3 PHP >= 7.0 and CMS 7.6-8.7}
\title{
Cheatsheet for test-driven development with PHPUnit
}
\begin{document}
\nocite*{}
\maketitle
\section*{License}
This handout is licensed under a \emph{Creative Commons} license, in this case under an \emph{Attribution-ShareAlike~4.0 (CC BY-SA 4.0)}. This means that you can use, edit and distribute this handout (even commercially) under the following conditions:
\begin{description}
\item[Attribution.] You need to give credit to the author (me) by listing my name (Oliver Klee). If you also list the source\footnote{\url{https://github.com/oliverklee/tdd-reader}}, that would be nice. And if you want to make me happy, please drop me an e-mail if you use this document.
\item[ShareAlike.] If you edit or change this document or use it as a basis for some other document, you must use the same license for the resulting document.
\item[Name the license.] If you distribute this document, you will need to mention or enclose the license.
\end{description}
You can find a more comprehensive version of this license online.\footnote{\url{http://creativecommons.org/licenses/by-sa/4.0/}}
\pagebreak
\tableofcontents
\pagebreak
\section{Test levels and types}
Thanks for of these concepts go to Filip Defar who wrote about this in his blog\footnote{\url{http://filipdefar.com/2015/06/tested-be-thy-name.html}}.
\subsection{Test levels}
\paragraph{Unit tests} are small and execute fast. They also usually are the fastest to write. You use them to test every detail of your application, including things that cannot be tested at the GUI level. There are a few cases where unit tests do not make much sense, e.\,g., queries in Extbase repositories. Please note that \emph{unit tests} also sometimes is used for all tests that are executed with a unit-testing framework (including system tests).
\paragraph{Integration tests} are slower to execute. You use them to test how components work together. Usually, you do not test every detail with them. In the TYPO3 world, these tests are called \fett{functional tests}.
\paragraph{System tests} are the biggest and the slowest to execute. You use those to test you application as a whole. They are used to test few bigger use cases.
\subsection{Test types}
\paragraph{Black-box tests} test how a unit or API behaves on the outside. No knowledge about the way it works inside is assumed. Black-box tests facilitate refactoring. They are one extreme of a continuum where white-box tests are the other extreme.
\paragraph{White-box tests} test how a unit works on the inside. They obstruct refactoring and are not recommended. They are one extreme of a continuum where black-box tests are the other extreme. Usually, tests should be black-box (or a very dark gray).
\paragraph{Functional tests} test the behavior of a unit. Most tests are functional tests. Note: In the TYPO3 world, \emph{functional test} actually means \emph{integration test} (and sometimes \emph{system test}).
\paragraph{Acceptance tests} test how the application works on the GUI level (or in the web interface). Sometimes this term is used as a synonym for \emph{story tests}.
\paragraph{Regression tests} test that bugs to not reappear. In the optimal case, they are written together with the corresponding bug fix.
\paragraph{Smoke tests} test that your application runs at all.
\paragraph{Story tests} test use cases for user stories. Usually, they are written in the \emph{Gherkin} language for behavior-driven design (BDD). These test sometimes also are called \emph{acceptance tests}.
\section{Test phases}
Within the test methods, the code for the test phases should be separated by blank lines to make the structure easily visible.
\hspace{1em}
\begin{tabular}{l l}
\emph{Setup} & \texttt{setUp()} and code at the beginning of the method (if needed) \\
\emph{Exercise} & Method call \\
\emph{Verify} & \texttt{self::assert…()} \\
\emph{Teardown} & \texttt{tearDown()} \\
\end{tabular}
\section{PhpStorm plug-ins}
These two plug-ins for PhpStorm are particularly helpful when creating unit tests:
\begin{itemize}
\item PHPUnit Autocomplete Assistant\footnote{\url{https://plugins.jetbrains.com/plugin/7722-phpunit-autocomplete-assistant}}
\item DynamicReturnTypePlugin\footnote{\url{https://plugins.jetbrains.com/plugin/7251-dynamicreturntypeplugin}}
\end{itemize}
\section{File and class naming}
\subsection{File names}
\begin{tabular}{|l|l|}
\hline
\fett{Production code file name} & \fett{Test file name} \\
\hline
\texttt{Classes/Domain/Model/Shoe.php} & \texttt{Tests/Unit/Domain/Model/ShoeTest.php} \\
\hline
\texttt{Classes/Service/BaristaService.php} & \texttt{Tests/Unit/Service/BaristaServiceTest.php} \\
\hline
\end{tabular}
\subsection{Class names}
\small
\begin{tabular}{|l|l|}
\hline
\fett{Production code class name} & \fett{Test class name} \\
\hline
\texttt{Shoes\textbackslash Shop\textbackslash Domain\textbackslash Model\textbackslash Shoe} & \texttt{Shoes\textbackslash Shop\textbackslash Tests\textbackslash Unit\textbackslash Domain\textbackslash Model\textbackslash ShoeTest} \\
\hline
\texttt{Shoes\textbackslash Shop\textbackslash Service\textbackslash BaristaService} & \texttt{Shoes\textbackslash Shop\textbackslash Tests\textbackslash Unit\textbackslash Service\textbackslash BaristaServiceTest} \\
\hline
\end{tabular}
\normalsize
\pagebreak
\section{Test class structure}
\subsection{Test base class}
\subsubsection{Non-TYPO3 project}
\paragraph{PHPUnit <= 5.7} \texttt{\textbackslash PHPUnit\_Framework\_TestCase}
\paragraph{PHPUnit >= 6.0} \texttt{\textbackslash PHPUnit\textbackslash Framework\textbackslash TestCase}
\subsubsection{TYPO3 project}
\subsubsection{With \texttt{nimut/testing-framework}}
\paragraph{Unit tests}
\texttt{\textbackslash Nimut\textbackslash TestingFramework\textbackslash TestCase\textbackslash UnitTestCase}
\paragraph{ViewHelper tests}
\texttt{\textbackslash Nimut\textbackslash TestingFramework\textbackslash TestCase\textbackslash ViewHelperBaseTestcase}
\paragraph{Functional tests}
\texttt{\textbackslash Nimut\textbackslash TestingFramework\textbackslash TestCase\textbackslash FunctionalTestCase}
\subsubsection{With \texttt{typo3/testing-framework}}
\paragraph{Unit tests}
\texttt{\textbackslash TYPO3\textbackslash TestingFramework\textbackslash Core\textbackslash Unit\textbackslash UnitTestCase}
\paragraph{Functional tests}
\texttt{\textbackslash TYPO3\textbackslash TestingFramework\textbackslash Core\textbackslash Unit\textbackslash FunctionalTestCase}
\subsection{Non-TYPO3 PHP projects with Composer}
There is an empty starter project for this on GitHub:\\
\url{https://github.com/oliverklee/tdd-seed}
\subsubsection{composer.json}
This setup installs PHPUnit and vfsStream:
\begin{jsoncode}
{
"require-dev": {
"phpunit/phpunit": "^6.3",
"mikey179/vfsstream": "^1.6"
},
"autoload": {
"psr-4": {
"..."
}
},
"autoload-dev": {
"psr-4": {
"..."
}
}
}
\end{jsoncode}
\subsubsection{Test case}
\begin{phpcode}
namespace OliverKlee\Books\Tests\Unit\Domain\Model;
use OliverKlee\Books\Domain\Model;
class BookTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Book
*/
protected $subject = null;
protected function setUp()
{
$this->subject = new Book();
}
/**
* @test
*/
public function getTitleInitiallyReturnsEmptyString()
{
self::assertSame('', $this->subject->getTitle());
}
/**
* @test
*/
public function setTitleSetsTitle()
{
$title = 'foo bar';
$this->subject->setTitle($title);
self::assertSame('foo bar', $this->subject->getTitle());
}
}
\end{phpcode}
\subsection{Extbase extensions}
There is an example project (the tea example) for this on GitHub:\\
\url{https://github.com/oliverklee/ext_tea}
\begin{phpcode}
namespace OliverKlee\Shop\Tests\Unit\Domain\Model;
use OliverKlee\Shop\Domain\Model\Article;
class ArticleTest extends \Nimut\TestingFramework\TestCase\UnitTestCase {
/**
* @var Article;
*/
protected $subject = null;
protected function setUp()
{
$this->subject = new Article;
$this->subject->initializeObject();
}
/**
* @test
*/
public function getNameInitiallyReturnsEmptyString()
{
self::assertSame('', $this->subject->getName());
}
/**
* @test
*/
public function setNameSetsName()
{
$name = 'foo bar';
$this->subject->setName($name);
self::assertSame($name, $this->subject->getName());
}
// ...
}
\end{phpcode}
\pagebreak
\section{Executing the tests}
\subsection{Non-TYPO3 projects}
\subsubsection{On the command line}
\begin{bashcode}
vendor/bin/phpunit Tests/
\end{bashcode}
\subsubsection{Within PhpStorm}
\begin{enumerate}
\item Settings > Languages \& Frameworks > PHP > PHPUnit
\item PHPUnit library > Use Composer autoloader
\item PHPUnit library > Path to script: \texttt{vendor/autoload}
\item OK
\item right-click on the \texttt{Tests/} folder (or any test file or folder)
\item Run 'Tests'
\end{enumerate}
\subsection{TYPO3 core}
In the TYPO3 wiki, there are how-tos on how to run the unit tests\footnote{\url{https://wiki.typo3.org/Unit_Testing_TYPO3}} and the functional tests\footnote{\url{https://wiki.typo3.org/Functional_testing}} of the TYPO3 core.
\subsection{TYPO3 extensions}
\subsubsection{Within PhpStorm}
\paragraph{For an existing TYPO3 installation in Composer mode:}
This will also load all existing extensions (including the PHPUnit extension), making it possible to use the features of the PHPUnit extension.
\begin{enumerate}
\item Settings > Languages \& Frameworks > PHP > PHPUnit
\item PHPUnit library > Use Composer autoloader
\item PHPUnit library > Path to script: \texttt{vendor/autoload} within the TYPO3 document root
\item OK
\item Run > Edit Configurations
\item Defaults > PHPUnit
\item Use alternative configuration file: \texttt{…/vendor/nimut/testing-framework/res/Configuration/UnitTests.xml} or \texttt{…/vendor/nimut/testing-framework/res/Configuration/FunctionalTests.xml}
\item Command Line > Environment variables
\item add four variables (only necessary for functional tests):
\begin{itemize}
\item \texttt{typo3DatabaseUsername}
\item \texttt{typo3DatabasePassword}
\item \texttt{typo3DatabaseHost} (usually \texttt{localhost})
\item \texttt{typo3DatabaseName}
\end{itemize}
\item OK
\item right-click on the \texttt{Tests/} folder (or any test file or folder)
\item Run 'Tests'
\end{enumerate}
\paragraph{For an existing TYPO3 installation in classic mode (non-Composer mode):}
In this case, you will not be able to autoload any classes from other extensions, i.\,e., you will not be able to use any features of the PHPUnit extension (or of any other extension dependencies).
\begin{enumerate}
\item If you have downloaded the TYPO3 source via git instead of as a TAR package, you will need to do a \texttt{composer install} in the TYPO3 source directory.
\item Settings > Languages \& Frameworks > PHP > PHPUnit
\item PHPUnit library > Use Composer autoloader
\item PHPUnit library > Path to script: \texttt{vendor/autoload} within the TYPO3 source
\item OK
\item Run > Edit Configurations
\item Defaults > PHPUnit
\item Use alternative configuration file: \texttt{…/vendor/nimut/testing-framework/res/Configuration/UnitTests.xml} or \texttt{…/vendor/nimut/testing-framework/res/Configuration/FunctionalTests.xml}
\item Command Line > Environment variables
\item add four variables (only necessary for functional tests):
\begin{itemize}
\item \texttt{typo3DatabaseUsername}
\item \texttt{typo3DatabasePassword}
\item \texttt{typo3DatabaseHost} (usually \texttt{localhost})
\item \texttt{typo3DatabaseName}
\end{itemize}
\item right-click on the \texttt{Tests/} folder (or any test file or folder)
\item Run 'Tests'
\end{enumerate}
\paragraph{Without using an existing TYPO3 installation}
This is the approach used in the TYPO3 extension skeleton\footnote{\url{https://github.com/helhum/ext_scaffold}} by Helmut Hummel and Nicole Cordes.
Add the following sections the \texttt{composer.json} of your extension:
\small
\begin{jsoncode}
"require": {
"typo3/cms": "~7.6.0"
},
"require-dev": {
"namelesscoder/typo3-repository-client": "^1.2",
"nimut/testing-framework": "^2.0",
"phpunit/phpunit": "^5.7",
"mikey179/vfsstream": "^1.6"
},
"config": {
"vendor-dir": ".Build/vendor",
"bin-dir": ".Build/bin"
},
"scripts": {
"post-autoload-dump": [
"mkdir -p .Build/Web/typo3conf/ext/",
"[ -L .Build/Web/typo3conf/ext/tea ] || ln -snvf ../../../../. .Build/Web/typo3conf/ext/tea"
]
},
"extra": {
"typo3/cms": {
"cms-package-dir": "{$vendor-dir}/typo3/cms",
"web-dir": ".Build/Web"
}
}
\end{jsoncode}
\normalsize
You'll need to replace \texttt{tea} in line 18 with the key of your extension.
If you'd like to use other extensions that are available from the TER (e.\,g., the PHPUnit extension), you will need to add (or merge) these sections to your \texttt{composer.json}:
\begin{jsoncode}
"repositories": [
{
"type": "composer",
"url": "https://composer.typo3.org/"
}
],
"require-dev": {
"typo3-ter/phpunit": "^5.7.0"
},
\end{jsoncode}
Then do the following in PhpStorm:
\begin{enumerate}
\item Settings > Languages \& Frameworks > PHP > PHPUnit
\item PHPUnit library > Use Composer autoloader
\item PHPUnit library > Path to script:
\begin{itemize}
\item click on the \emph{Show hidden files and directories} button
\texttt{.Build/vendor/autoload.php} within the extension directory
\end{itemize}
\item OK
\item Run > Edit Configurations
\item Defaults > PHPUnit
\item Command Line > Environment variables
\item add four variables (only necessary for functional tests):
\begin{itemize}
\item \texttt{typo3DatabaseUsername}
\item \texttt{typo3DatabasePassword}
\item \texttt{typo3DatabaseHost} (usually \texttt{localhost})
\item \texttt{typo3DatabaseName}
\end{itemize}
\item right-click on the \texttt{Tests/} folder (or any test file or folder)
\item Run 'Tests'
\end{enumerate}
\pagebreak
\section{Mocks}
\subsection{Why mock?}
\begin{itemize}
\item to ``disable'' a method (to not write to the DB, or to not launch a cruise missile) and return null
\item to have a method return a particular return value or throw an exception
\item to test that a method gets called in a certain way
\end{itemize}
\subsection{Tools for mocking}
\paragraph{Prophecy:} The recommended, state-of the art, easy-to-use mocking framework. It cannot create partial mocks, though.\footnote{Prophecy cheatsheet:\\ \url{https://github.com/oliverklee/tdd-reader/blob/master/AdditionalDocuments/prophecy-cheatsheet.pdf}}
\paragraph{PHPUnit mocks:} The old way of creating mocks. Creating mocks is a bit unwieldy, but it can create partial mocks.\footnote{PHPUnit mocking cheatsheet:\\ \url{https://github.com/oliverklee/tdd-reader/blob/master/AdditionalDocuments/mocking-cheatsheet.pdf}}
\paragraph{Mockery:} Also very elegant.\footnote{\url{https://github.com/mockery/mockery}}
\pagebreak
\section{Testing for Exceptions}
According to a 2016 blog post\footnote{\url{https://thephp.cc/news/2016/02/questioning-phpunit-best-practices}} by Sebastian Bergmann (the author of PHPUnit), this is current best practise.
\subsection{Test for the Exception class only}
\begin{phpcode}
/**
* @test
*/
public function createBreadWithNegativeSizeThrowsException()
{
$this->expectException(\UnexpectedValueException::class);
$this->subject->createBread(-1);
}
\end{phpcode}
\subsection{Test for the exception class, message and the code}
\begin{phpcode}
/**
* @test
*/
public function createBreadWithNegativeSizeThrowsException()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('$size must be > 0.');
$this->expectExceptionCode(1323700434);
$this->subject->createBread(-1);
}
\end{phpcode}
\section{Testing protected and private methods}
\subsection{Testing indirectly (recommended)}
Tests should only test the behavior that has effects that can be observed from the outside. So protected methods should be tested by tests for public methods that call the protected methods.
\subsection{Create a testing subclass}
If you have protected methods that explicitly are part of the API to be used in subclasses, you can create a testing subclass located in \texttt{Fixtures/} that provides a public method calling the protected method.
\pagebreak
\section{Testing abstract classes}
\subsection{Using the PHPUnit mock builder}
This will create an instance of the abstract class with all abstract methods mocked.
\begin{phpcode}
namespace OliverKlee\Coffee\Tests\Unit\Domain\Model;
use OliverKlee\Coffee\Domain\Model\AbstractBeverage;
class AbstractBeverageTest
{
/**
* @var AbstractBeverage|\PHPUnit_Framework_MockObject_MockObject
*/
protected $subject = null;
protected function setUp()
{
$this->subject = $this->getMockForAbstractClass(
AbstractBeverage::class
);
}
\end{phpcode}
\subsection{Creating a concrete subclass}
This is recommended if you need to provide your subclass with some additional or specific behavior.
In \texttt{Tests/Unit/Domain/Model/Fixtures/}, create a subclass of the abstract class:
\begin{phpcode}
namespace OliverKlee\Coffee\Tests\Unit\Domain\Model\Fixtures;
class TestingBeverage extends \OliverKlee\Coffee\Domain\Model\AbstractBeverage
{
// ...
}
\end{phpcode}
Then you can use and instantiate the concrete subclass in your unit tests:
\begin{phpcode}
use OliverKlee\Coffee\Tests\Unit\Domain\Model\Fixtures\TestingBeverage;
class AbstractBeverageTest
{
/**
* @var TestingBeverage
*
protected $subject = null;
protected function setUp()
{
$this->subject = new TestingBeverage();
}
\end{phpcode}
\pagebreak
\section{Using the testing framework of the PHPUnit TYPO3 extension}
\begin{phpcode}
class DataMapperTest extends \Tx_Phpunit_TestCase
{
/**
* @var \Tx_Phpunit_Framework
*/
protected $testingFramework = null;
protected $subject = null;
protected function setUp()
{
$this->testingFramework = new \Tx_Phpunit_Framework('tx_oelib');
$this->subject = new ...;
}
protected function tearDown()
{
$this->testingFramework->cleanUp();
}
/**
* @test
*/
public function findWithUidOfExistingRecordReturnsModelDataFromDatabase()
{
$title = 'foo';
$uid = $this->testingFramework->createRecord(
'tx_oelib_test', ['title' => $title]
);
self::assertSame($title, $this->subject->find($uid)->getTitle());
}
\end{phpcode}
\subsection{Executable examples}
The functional tests for the FileUtility class in the tea example\footnote{\url{https://github.com/oliverklee/ext_tea}} show what tests with vfsStream can look like.
\pagebreak
\section{Using mock file systems with vfsStream}
\subsection{Setting it all up}
\begin{phpcode}
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* @var \org\bovigo\vfs\vfsStreamFile
*/
protected $moreStuff;
protected function setUp()
{
// This is the same as ::register and ::setRoot.
$this->root = vfsStream::setup('home');
$this->targetFilePath = vfsStream::url('home/target.txt');
$this->subject = new ...
}
\end{phpcode}
\subsection{Using the files}
\begin{phpcode}
/**
* @test
*/
public function concatenateWithOneEmptySourceFileCreatesEmptyTargetFile()
{
// This is one way to create a file with contents, using PHP's file functions.
$sourceFileName = vfsStream::url('home/source.txt');
// Just calling vfsStream::url does not create the file yet.
// We need to write into it to create it.
file_put_contents($sourceFileName, '');
$this->subject->concatenate($this->targetFilePath, [$sourceFileName]);
self::assertSame('', file_get_contents($this->targetFilePath));
}
/**
* @test
*/
public function concatenateWithOneFileCopiesContentsFromSourceFileToTargetFile()
{
// This is vfsStream's way of creating a file with contents.
$contents = 'Hello world!';
$sourceFileName = vfsStream::url('home/source.txt');
vfsStream::newFile('source.txt')->at($this->root)->setContent($contents);
$this->subject->concatenate($this->targetFilePath, [$sourceFileName]);
self::assertSame($contents, file_get_contents($this->targetFilePath));
}
\end{phpcode}
\pagebreak
\section{Testing Extbase controllers}
For controllers that are built in a clean way, you will mostly only need to test that data is passed correctly from the request to the repositories and from the repositories to the views. In addition, you will occasionally want to tests forwards and redirects.
\subsection{Mocking and injecting repositories}
\begin{phpcode}
protected function setUp()
{
$this->subject = new TestimonialController();
$this->viewProphecy = $this->prophesize(ViewInterface::class);
$this->view = $this->viewProphecy->reveal();
$this->inject($this->subject, 'view', $this->view);
$this->testimonialRepositoryProphecy
= $this->prophesize(TestimonialRepository::class);
$this->testimonialRepository
= $this->testimonialRepositoryProphecy->reveal();
$this->inject(
$this->subject,
'testimonialRepository',
$this->testimonialRepository
);
}
\end{phpcode}
The \texttt{inject} method is a helper method from the test case base class.
If you are using explicit \texttt{inject…} method in the controller for better performance (instead the \texttt{@inject} annotations), you can use the inject methods:
\begin{phpcode}
$this->subject->injectTestimonialRepository($this->testimonialRepository);
\end{phpcode}
\subsection{Testing the data flow from the repository to the view}
\begin{phpcode}
/**
* @test
*/
public function indexActionPassesAllTestimonialsAsTestimonialsToView()
{
$allTestimonials = new ObjectStorage();
$this->testimonialRepositoryProphecy->findAll()
->willReturn($allTestimonials);
$this->viewProphecy->assign('testimonials', $allTestimonials)
->shouldBeCalled();
$this->subject->indexAction();
}
\end{phpcode}
\pagebreak
\section{PHPUnit assertions}
This list is current for PHPUnit 6.3.x.
\begin{verbatim}
assertArrayHasKey()
assertClassHasAttribute()
assertArraySubset()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertContainsOnlyInstancesOf()
assertCount()
assertDirectoryExists()
assertDirectoryIsReadable()
assertDirectoryIsWritable()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertFileIsReadable()
assertFileIsWritable()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInfinite()
assertInstanceOf()
assertInternalType()
assertIsReadable()
assertIsWritable()
assertJsonFileEqualsJsonFile()
assertJsonStringEqualsJsonFile()
assertJsonStringEqualsJsonString()
assertLessThan()
assertLessThanOrEqual()
assertNan()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertThat()
assertTrue()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
\end{verbatim}
\bibliography{tdd-reader}
\end{document}