Anna Filina
PRO
May 25, 2016
170

# Unit Testing By Example

Everyone says you need to test. You know the theory, but you do not know where to begin. What should you test? What cases should you write? Using realistic, pragmatic examples, this presentation will take you away from var_dump and ease you into the testing business until you are ready to do TDD without losing sight of tight deadlines.

May 25, 2016

## Transcript

1. ### foolab.ca | @foolabca Unit Testing by Example php[tek], St. Louis

- May 25, 2016
2. ### Objectives • Make testing enjoyable. • Make it useful. •

Reduce pre-release stress. 2
3. ### Anna Filina • Developer • Problem solver • Teacher •

Advisor • FooLab + ConFoo 3

7. ### Step 1: Found Bug \$item = new CartItem("Overwatch", 30); \$item->setQuantity(0.1);

\$this->assertEquals(1, \$item->getQuantity()); 7
8. ### Step 1: Found Bug \$item = new CartItem("Overwatch", 30); \$item->setQuantity(0.1);

\$this->assertEquals(1, \$item->getQuantity()); public function setQuantity(\$qty) { \$this->qty = ceil(\$qty); } 8

11. ### Step 2: Improve Code public function getShipping() { if (\$this->subtotal

>= 40) { return 0; } else { return 15; } } 11
12. ### Test Both Cases \$item = new CartItem("Overwatch", 30); \$item->setQuantity(1); \$cart->addItem(\$item);

\$this->assertEquals(15, \$cart->getShipping()); 12
13. ### Step 3: New Code public function getTotal() { //... \$taxes

= \$this->getApplicableTaxes(); foreach (\$taxes as \$tax) { \$total += \$subtotal * \$tax->getPercent(); } //... } 13
14. ### Step 3: New Code array (size=2) 0 => array (size=2)

'name' => string 'GST' (length=3) 'percent' => float 0.05 1 => array (size=2) 'name' => string 'QST' (length=3) 'percent' => float 0.09975 14
15. ### Step 3: New Code \$cart = new Cart(); \$taxes =

\$cart->getApplicableTaxes(); \$this->assertInternalType('array', \$taxes); \$this->assertCount(2, \$taxes); \$gst = \$taxes[0]; \$this->assertEquals(0.05, \$gst['percent']); 15
16. ### Advantages • More tests. • Easy to write. • Never

fall too far. 16

19. ### Tips • How it’s not supposed to work. • Plan

for exceptions. • Focus on realistic scenarios. 19

23. ### Execution Paths public function getShipping() { if (\$this->subtotal >= 40)

{ return 0; } return \$this->shipping; } 23

25. ### Zero Times foreach (\$products as \$product) { \$total = \$product->price

* \$product->quantity; } if (\$total > 0) { echo 'found'; } 25
26. ### Multiple Times \$total = 0; foreach (\$products as \$product) {

\$total = \$product->price * \$product->quantity; } if (\$total > 0) { echo 'found'; } 26
27. ### Recap • Testing takes practice. • Write tests when you

see a bug. • Write tests when you improve code.  • Write tests as you write new code. • Write tests before you write code. • Test unexpected scenarios. 27
28. ### Anna Filina • Development. • Fix bugs & performance issues.

• Workshops on testing, frameworks & APIs. • Advisor on testing strategy, legacy code. 28