Why Should I Test? • Don‘t we already test our code? • F5-Driven Development – Feedback Loop (var dump etc…) • Pray on deployment 13.10.2017 www.silverstrip.es 4
Quotes • Tests for a project mean that at least somebody used to care at some point about what they were doing (Chris Hartjes) 13.10.2017 www.silverstrip.es 6
Contra Testing • Writing tests takes more time • You have to reason about what you‘re doing • It‘s not easy to write good and meaningful tests • No 100% guarantee that your code is bug free 13.10.2017 www.silverstrip.es 12
Contra Testing #2 • Running them takes a long time (DB connection is slow) • I‘m the only one in the company that runs my tests • You have to change your habbits 13.10.2017 www.silverstrip.es 13
Pro Testing • It‘s just code – and we know how to code • Repeatable – don‘t throw away your (manual) tests • Future investment • 90% less bugs in production • Bugs are found during development phase, not after shipping – That‘s cheaper 13.10.2017 www.silverstrip.es 14
Pro Testing #2 • Makes you reason about your code – Structure – How the code should solve the given problem • Documentation of how your code is supposed to work • Makes you a better developer • Refactoring becomes easier 13.10.2017 www.silverstrip.es 15
Types Of Tests • Unit tests – Small units of your code, usually a method • Component tests – Bigger unit, – might use database – takes longer to run • Functional test – End to end, incl. GET / POST request etc.. 13.10.2017 www.silverstrip.es 21
Test Driven Development (TDD) • Write your test first • Run that test – Watch it failing • Write code to fulfill your test • Run the test again – Watch it passing • Refactor your code 13.10.2017 www.silverstrip.es 23
TDD Pro • Fast Feedback loop with small iterations • Design your code in a testable manner • More modular • Cleaner interfaces • „Stupid“ mistakes are found immediately 13.10.2017 www.silverstrip.es 26
Testing A Legacy Project • Code might be harder to test • You have to reason about the existing code • Tests create a backlog for technical debt – Technial debt is a bad thing that backfires. Always • Proof that legacy code works – or not • A safeguard for refactoring 13.10.2017 www.silverstrip.es 30
PHPUnit Conventions • Naming: – Class Email – Test class: EmailTest • A test method starts with „test“, e.g. testEmailSentWhenNewUserRegisters() 13.10.2017 www.silverstrip.es 33
Data Providers • Write more generic tests, feed different data to it • You can reuse them, also call from different classes 13.10.2017 www.silverstrip.es 37
About me • Werner M. Krauß • Located in Hallstatt, Austria • wmk on IRC slack / github / stackoverflow • PHP since 1998 • Freelancer since 2006 (netwerkstatt) • SilverStripe since 2009