phpunit episode iv.iii: return of the tests

Post on 15-Jul-2015

114 Views

Category:

Engineering

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

PHPunitEpisode IV.III!

Return of the tests

A long time ago, in a code base not so far away…

For years people have been advocating the usage of unit tests and slowly developers around the world have adopted the skills to write good tests. But since the crisis businesses have been battling for customers and profits, leaving less room for proper QA and testing. In this race for money, things are looking dim and unfavourable for businesses that have cut corners and went straight for the gold.

Fortunately it’s not to late for development teams to turn the tide and reclaim their honour and ensure businesses aren’t disposing money out of the window because of easily preventable failures. The gloves are on and developers take action to test what’s most important: the core of the applications!

Auth ACL

Products

CustomerDetails

Front-End

Back-End

BusinessLogic

ExternalServices

RDBMS

Files

NoSQL

Streams

Auth ACL

BusinessLogic

ExternalServices

Auth ACL

BusinessLogic

ExternalServices

Mocked!External!Services

http

s://w

ww.

flick

r.com

/pho

tos/

nood

lepi

e/38

8651

9163

http

s://w

ww.

flick

r.com

/pho

tos/

csee

man

/111

0192

0756

http

s://w

ww.

flick

r.com

/pho

tos/

st3f

4n/3

7529

9477

8

Your class contains 10K lines!I sense lots of anger in you

http

s://w

ww.

flick

r.com

/pho

tos/

clem

ent1

27/1

6162

2272

60

• createOrder

• updateOrder

• payOrder

• cancelOrder

• findOrderById

• findOrderByCustomerId

• findOrderByPaymentId

• createOrder

• updateOrder

• payOrder

• findOrderByPaymentId

• findOrderByCustomerId

• findOrderById

• cancelOrder

} High importance

} Normal importance

} Low importance

    /** "     * Creates an order based on provided data "     * "     * @param array $data Associative array with order information "     * @return bool|int Will return the order ID if storage was successful "     * or false when storage failed "     */ "    public function createOrder($data) "    { "        $db = Registry::getInstance()->get('db'); "        $sql = sprintf( "            'INSERT INTO `order` (`productId`, `customerId`, "            `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "            $data['productId'], $data['customerId'], "            $data['productPrice'], $data['quantity'] "        ); "        $id = false; "        try { "            $id = $db->exec($sql); "        } catch (Exception $e) { "            Registry::get('logger')->log($e->getMessage(), CRIT); "            Registry::get('logger')->log($e->getTraceAsString(), INFO); "        } "        return $id; "    }

http

s://w

ww.

flick

r.com

/pho

tos/

sim

onon

ly/1

6445

2784

75

/** " * Creates an order based on provided data " * " * @param array $data Associative array with order information " * @return bool|int Will return the order ID if storage was successful  " * or false when storage failed " */ "public function createOrder($data) "{ "    $db = Registry::get('db'); "    $sql = sprintf( "        'INSERT INTO `order` (`productId`, `customerId`,  "        `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "        $data['productId'], $data['customerId'],  "        $data['productPrice'], $data['quantity'] "    ); "    $id = false; "    try { "        $id = $db->query($sql); "    } catch (Exception $e) { "        Registry::get('logger')->log($e->getMessage(), CRIT); "        Registry::get('logger')->log($e->getTraceAsString(), INFO); "    } "    return $id; "}

/** " * Creates an order based on provided data " * " * @param array $data Associative array with order information " * @return bool|int Will return the order ID if storage was successful  " * or false when storage failed " */ "public function createOrder($data) "{ "    $db = Registry::get('db'); "    $sql = sprintf( "        'INSERT INTO `order` (`productId`, `customerId`,  "        `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "        $data['productId'], $data['customerId'],  "        $data['productPrice'], $data['quantity'] "    ); "    $id = false; "    try { "        $id = $db->query($sql); "    } catch (Exception $e) { "        Registry::get('logger')->log($e->getMessage(), CRIT); "        Registry::get('logger')->log($e->getTraceAsString(), INFO); "    } "    return $id; "}

/** " * Creates an order based on provided data " * " * @param array $data Associative array with order information " * @return bool|int Will return the order ID if storage was successful  " * or false when storage failed " */ "public function createOrder($data) "{ "    $db = Registry::get('db'); "    $sql = sprintf( "        'INSERT INTO `order` (`productId`, `customerId`,  "        `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "        $data['productId'], $data['customerId'],  "        $data['productPrice'], $data['quantity'] "    ); "    $id = false; "    try { "        $id = $db->query($sql); "    } catch (Exception $e) { "        Registry::get('logger')->log($e->getMessage(), CRIT); "        Registry::get('logger')->log($e->getTraceAsString(), INFO); "    } "    return $id; "}

What do we know?

What do we know?

• We provide an array with values in

What do we know?

• We provide an array with values in

• We get inserted ID or false back

What do we know?

• We provide an array with values in

• We get inserted ID or false back

• The code is crappy

class OrderTest extends \PHPUnit_Framework_TestCase "{ "    public function testCreateOrder() "    { "        $data = array ( "            'productId' => 1, "            'customerId' => 1, "            'productPrice' => 4.95, "            'quantity' => 2, "        ); "        $order = new Order(); "        $result = $order->createOrder($data); "        $this->assertGreaterThanOrEqual(1, $result); "    } "}

    public function testCreateOrder() "    { "        $db = new \PDO('sqlite::memory:'); "        $db->exec('CREATE TABLE `order` ( "          `orderId` INTEGER PRIMARY KEY NOT NULL, "          `productId` INTEGER NOT NULL, "          `customerId` INTEGER NOT NULL, "          `productPrice` REAL NOT NULL DEFAULT 0.0, "          `quantity` REAL NOT NULL DEFAULT 1.0);'); "        Registry::getInstance()->register('db', $db); "        $data = array ( "            'productId' => 1, "            'customerId' => 1, "            'productPrice' => 4.95, "            'quantity' => 2, "        ); "        $order = new Order(); "        $result = $order->createOrder($data); "        $this->assertGreaterThanOrEqual(1, $result); "    }

http

s://w

ww.

flick

r.com

/pho

tos/

jurv

etso

n/83

1769

15

    public function testCreateOrder() "    { "        $db = $this->getMock('\\PDO',  "            array ('exec'), array ('sqlite::memory:')); "        $db->expects($this->once()) "            ->method('exec') "            ->will($this->returnValue(2)); "!        Registry::getInstance()->register('db', $db); "        $data = array ( "            'productId' => 1, "            'customerId' => 1, "            'productPrice' => 4.95, "            'quantity' => 2, "        ); "        $order = new Order(); "        $result = $order->createOrder($data); "        $this->assertGreaterThanOrEqual(1, $result); "    }

http

s://w

ww.

flick

r.com

/pho

tos/

lego

fenr

is/4

5784

5356

9

    /** "     * @var \PDO "     */ "    protected $db; "!    /** "     * @return \PDO "     */ "    public function getDb() "    { "        if (null === $this->db) { "            // fallback to old functions using this method "            $this->setDb(Registry::getInstance()->get('db')); "        } "        return $this->db; "    } "!    /** "     * @param \PDO $db "     */ "    public function setDb($db) "    { "        $this->db = $db; "    }

    /** "     * Creates an order based on provided data "     * "     * @param array $data Associative array with order information "     * @return bool|int Will return the order ID if storage was successful "     * or false when storage failed "     */ "    public function createOrder($data) "    { "        $db = $this->getDb(); "        $sql = sprintf( "            'INSERT INTO `order` (`productId`, `customerId`, "            `productPrice`, `quantity`) VALUES (%d, %d, %f, %f)', "            $data['productId'], $data['customerId'], "            $data['productPrice'], $data['quantity'] "        ); "        $id = false; "        try { "            $id = $db->exec($sql); "        } catch (Exception $e) { "            Registry::get('logger')->log($e->getMessage(), CRIT); "            Registry::get('logger')->log($e->getTraceAsString(), INFO); "        } "        return $id; "    }

http

s://w

ww.

flick

r.com

/pho

tos/

pasu

karu

76/5

1524

9797

3

Michelangelo van Dam

dragonbe@gmail

T DragonBe

F DragonBe

www.dragonbe.com

Intergalactic PHP Ninja Consultant

http

s://w

ww.

flick

r.com

/pho

tos/

1301

6024

6@N

02/1

6465

3675

56

joind.in/event/view/3701

Rate my talk If you liked it, thanks.

If you don’t, tell me how to improve it

http

s://w

ww.

flick

r.com

/pho

tos/

toom

uchd

ew/1

4508

5647

45

top related