Tuesday, February 26, 2008. Unit testen in de praktijk



Similar documents
Specification by Example (methoden, technieken en tools) Remco Snelders Product owner & Business analyst

Testgetriebene Entwicklung mit PHPUnit. PHP Professional Training 22 th of November 2007

Examen Software Engineering /09/2011

Technical Specification ideal

Oversight Management: een zinvolle aanvulling!

Load Balancing Lync Jaap Wesselius

GMP-Z Annex 15: Kwalificatie en validatie

Dynamische Websites. Week 7

Maximizer Synergy. BE Houwaartstraat 200/1 BE 3270 Scherpenheuvel. Tel: Fax:

Virtualisatie. voor desktop en beginners. Gert Schepens Slides & Notities op gertschepens.be

The Importance of Collaboration

Word -Introduction. Contents

OGH: : 11g in de praktijk

The information in this report is confidential. So keep this report in a safe place!

Dutch Mortgage Market Pricing On the NMa report. Marco Haan University of Groningen November 18, 2011

Ontwikkeling van applicatie software: het nieuwe alternatief!

Sebastian Bergmann. Has instrumentally contributed to tranforming PHP into a reliable platform for large-scale, critical projects.

Research Report. Ingelien Poutsma Marnienke van der Maal Sabina Idler

Serious Game for Amsterdam Nieuw-West

APEX World 2013 APEX & Christian Rokitta. OGh APEX World 9 April 2013

QAFE. Oracle Gebruikersclub Holland Rokesh Jankie Qualogy. Friday, April 16, 2010

Verticale tuin maken van een pallet

Asking what. a person looks like some persons look like

~ We are all goddesses, the only problem is that we forget that when we grow up ~

NL VMUG UserCon March

Succevolle testautomatisering? Geen kwestie van geluk maar van wijsheid!

Penetration Testing with Selenium. OWASP 14 January The OWASP Foundation

SALES KIT. Richtlijnen verkooptools en accreditatieproces Voyages-sncf.eu. Vertrouwelijk document. Eigendom van de VSC Groep

CO-BRANDING RICHTLIJNEN

Windows Azure Push Notifications

Citrix Access Gateway: Implementing Enterprise Edition Feature 9.0

Logging en Monitoring - privacy, beveiliging en compliance Enkele praktijkvoorbeelden

Information technology specialist (systems integration) Informatietechnologie specialist (systeemintegratie) Professional activities/tasks

HOE WERKT CYBERCRIME EN WAT KAN JE ER TEGEN DOEN? Dave Maasland Managing Director ESET Nederland

Java GPU Computing. Maarten Steur & Arjan Lamers

listboxgaatmee.dragdrop += new DragEventHandler(listBox_DragDrop); ListBox from = (ListBox)e.Data.GetData(typeof(ListBox));

Constructief omgaan met conflicten

GMP-Z Hoofdstuk 4 Documentatie. Inleiding

PHPUnit Manual. Sebastian Bergmann

Citrix XenApp and XenDesktop Fast Track

Public. Big Data in ASML. Durk van der Ploeg. ASML System Engineering Product Industrialization, October 7, 2014 NTS Eindhoven

Shopper Marketing Model: case Chocomel Hot. Eric van Blanken 20th October 2009

Uw partner in system management oplossingen

IP-NBM. Copyright Capgemini All Rights Reserved

NEW PROGRAMMED ITEMS

Risk-Based Monitoring

Cursor 10 (24 jan 2013) Pagina 1

ElektorLive Eindhoven 20 november 2010

Met wie moet je als erasmusstudent het eerst contact opnemen als je aankomt?

ITCulinair Cisco InterCloud

How To Learn To Learn

T h e N e x t G e n e r a t i o n of C o n s u m e r i z a t i o n KIXS. Leading Edge Forum Study Tour October 2013

Hello friends, This is Aaditya Purani and i will show you how to Bypass PHP LFI(Local File Inclusion)

UvA college Governance and Portfolio Management

The new release of Oracle BI 11g R1

Sustainability Impact Assessment Tool

How To Test A Website On A Web Browser

Workshop(TestNet(( Najaarsevemenent(2014(

From QMS to IMS. Name: Arie Boer Function Risk Manager Date: 19 december 2014

Innovatiekracht van het MKB. Prof. Dr. Dries Faems Full Professor Innovation & Organization University of Groningen d.l.m.faems@rug.

THE EMOTIONAL VALUE OF PAID FOR MAGAZINES. Intomart GfK 2013 Emotionele Waarde Betaald vs. Gratis Tijdschrift April

Univé customer survey: Pay-As-You-Drive (PAYD) insurance

EEN HUIS BESTUREN ALS EEN FABRIEK,

Fail early, fail often, succeed sooner!

Franchise bij goederenverzekering PDF

Making, Moving and Shaking a Community of Young Global Citizens Resultaten Nulmeting GET IT DONE

Dutch Style Guide for Community

AANMELDING. International student - Berkeley College

Hoorcollege marketing 5 de uitgebreide marketingmix. Sunday, December 9, 12

Database: Data > add new datasource ALGEMEEN

Sample test Secretaries/administrative. Secretarial Staff Administrative Staff

Uniface en PostgreSQL, de eerste ervaringen

De tarieven van Proximus Niet meer gecommercialiseerde Bizz packs

Vibe OnPrem 3.x Makes the Business work!

Presentation about Worknets on the Bridge-IT conference. Barcelona, March 2011

Web Applications Testing

Jiří Tomeš. Nástroje pro vývoj a monitorování SW (NSWI026)

101 Inspirerende Quotes - Eelco de boer - winst.nl/ebooks/ Inleiding

Daan & Rembrandt Research Wendelien Daan By Willemijn Jongbloed Group D October 2009

The state of DIY. Mix Express DIY event Maarssen 14 mei 2014

Ons privacybier. Derde privacycafé Data Protection Institute 13 januari 2016 Thomas More Mechelen 21/01/16

DORI in de praktijk Paul van Dooren Sales District Manager

Test Automation Integration with Test Management QAComplete

Design Document. Developing a Recruitment campaign for IKEA. Solve-

IMPLEMENTATIE PAL4 DEMENTIE BIJ CLIENTEN VAN ZORGORGANISATIE BEWEGING 3.0

VIDEO CREATIVE IN A DIGITAL WORLD Digital analytics afternoon. Hugo.schurink@millwardbrown.com emmy.brand@millwardbrown.com

Lean Six Sigma Assessment Tool

CMMI version 1.3. How agile is CMMI?

INSPIRE FOSS Workshop. Just van den Broecke - just@justobjects.nl Haico van der Vegt

Coevolution of Software and Tests

password, just as if you were accessing the SharePoint environment with a browser. This prompting is also handled via Windows.

Server-side: PHP and MySQL (continued)

Career Guide. Career Guide. Faculty of Spatial Sciences

Magento Test Automation Framework User's Guide

Voorbeeld. Preview ISO INTERNATIONAL STANDARD. Cranes Requirements for test loads

Transcription:

Unit testen in de praktijk

Indeling Algemene theorie van unit testing PHPunit

Wat is het doel van testen? Controleren of software correct werkt. Voldoet software aan vooraf gegeven specificaties? Blijft software correct werken na veranderingen?

Beperkingen van testen Het testen van een programma is een effectieve manier om de aanwezigheid van fouten in een programma aan te tonen, maar het is volkomen inadequaat om hun afwezigheid te bewijzen. Edsger W. Dijkstra 'The Humble Programmer' 1972 (!)

Wat is unit testing? Manier om na te gaan of een individueel onderdeel van een stuk software naar behoren werkt. Methode Klasse Module Compleet systeem 'Verdeel en heers'

Wat is unittesting Bij een gegeven input, is de output wat verwacht wordt? Output is niet noodzakelijk de waarde die de functie zelf teruggeeft. Input is niet noodzakelijk de parameters die aan de functie worden meegegeven.

Output <?php class Transaction /** * Handles transactions from our webshop. * * @var paymentservice */ protected $paymentservice; public function pay($orderid) $this->paymentservice->startpayment(); $this->paymentservice->pay($orderid); return $this->paymentservice->checkstatus($orderid);

Input <?php class Transaction public function getunpayedorders() $orders = $this->paymentservice->getopenorders(); $unpayedorders = array(); foreach ($orders as $order) if ($order['status'] == 'unpayed') $unpayedorders[] = $order->id; return $unpayedorders;?>

Tests zijn software KISS DRY Test smells Test patterns

Test smells 'Er is iets mis met de tests' Symptoom, geen oorzaak. Code smells. Behavior smells. Project smells.

Code smells Obscure test. Hard-coded test data. Test code duplication.

Behavior Smells Interface sensitivity Behavior sensitivity Data sensitivity Context sensitivity Frequent debugging Slow tests

Project smells Production bugs Buggy tests High test maintenance cost

Test patterns Assertion Fixture Test double Setup Teardown Test suite Test runner

Testbaarheid Test voor of terwijl je code schrijft, niet erna. Houd rekening met testbaarheid tijdens het schrijven van de code. Verdeel en test.

PHP Unit testing Simpletest PHPUnit Lime (Symphony) PHPT

PHPUnit Lid van de xunit familie: JUnit, NUnit, PyUnit Uitgebreid gedocumenteerd Veel voorbeelden beschikbaar Beste keuze voor PHP

Basis unit test <?php //File class.transaction.php class Transaction public function pay($orderid) $this->paymentservice->startpayment(); $this->paymentservice->pay($orderid); return $this->paymentservice->checkstatus($orderid); <?php require_once 'source/class.transaction.php'; //File class.transactiontest.php class TransactionTest extends PHPUnit_Framework_TestCase //Removed code for clarity. public function testpay() $orderid = 1; $result = $this->transaction->pay($orderid); $this->assertequals('success', $result, '');

Basis unit test Voer een functie uit. Controleer output met een assertxxx(). Assert parameters: Expected, Actual, Message. Assert parameters: Actual, Message

Massa's assertwhatever().. $this->assertarrayhaskey(); $this->assertclasshasattribute(); $this->assertclasshasstaticattribute(); $this->assertcontains(); $this->assertcontainsonly(); $this->assertequalxmlstructure(); $this->assertequals(); $this->assertfalse(); $this->assertfileequals(); $this->assertfileexists(); $this->assertgreaterthan(); $this->assertgreaterthanorequal(); $this->assertlessthan(); $this->assertlessthanorequal(); $this->assertnotnull(); $this->assertobjecthasattribute(); $this->assertregexp();

Massa's assertwhatever().. $this->assertsame(); $this->assertselectcount(); $this->assertselectequals(); $this->assertselectregexp(); $this->assertstringequalsfile(); $this->asserttag(); $this->assertthat(); $this->asserttrue(); $this->asserttype(); $this->assertxmlfileequalsxmlfile(); $this->assertxmlstringequalsxmlfile();

pbouw test klasse <?php require_once 'source/class.transaction.php'; class TransactionTest extends PHPUnit_Framework_TestCase private $Transaction; //Prepares the environment before running a test. protected function setup() parent::setup (); $this->transaction = new Transaction(); // Cleans up the environment after running a test. protected function teardown() $this->transaction = null; parent::teardown (); // Test cases..

Test Doubles DOC (Depended Upon Component) Emuleren gedrag van een DOC. Stub emuleert DOC output. Mock controleert gebruik DOC.

Test Doubles <?php class Transaction protected $paymentservice; public function pay($orderid) //Do payment public function getunpayedorders() //Get a list of unpayed orders?>

Test Doubles (2) <?php class Transaction /** * Handles transactions from our webshop. * * @var paymentservice */ protected $paymentservice; //... public function pay($orderid) $this->paymentservice->startpayment(); $this->paymentservice->pay($orderid); return $this->paymentservice->checkstatus($orderid); //...?>

Test Doubles (3) <?php class paymentservice /** * Payment service. */ public function construct() /*.. */ public function startpayment() /*.. */ public function pay() /*.. */?> public function checkstatus() /*.. */ //...

Test Doubles (4) <?php require_once 'source/class.transaction.php'; require_once 'PHPUnit/Framework/TestCase.php'; class TransactionTest extends PHPUnit_Framework_TestCase private $Transaction; private $mockpaymentservice; //Prepares the environment before running a test. protected function setup() parent::setup (); $this->mockpaymentservice = $this->getmock('paymentservice', array('startpayment', 'pay', 'checkstatus', 'getunpayedorders')); $this->transaction = new Transaction($this->mockPaymentService); //...

Stub <?php require_once 'source/class.transaction.php'; require_once 'PHPUnit/Framework/TestCase.php'; class TransactionTest extends PHPUnit_Framework_TestCase //... public function testpay() $this->mockpaymentservice->expects($this->any()) - >method('checkstatus') ->will($this->returnvalue('success')); $result = $this->transaction->pay(1); $this->assertequals('success', $result, 'Payment for order 1 should always succeed'); //...

Mock <?php class TransactionTest extends PHPUnit_Framework_TestCase //... //Test Volgorde van aanroepen service public function testpaysequence() $orderid = '123'; $this->mockpaymentservice->expects($this->once()) - >method('startpayment'); $this->mockpaymentservice->expects($this->once()) - >method('pay') ->with($this->equalto($orderid)); $this->mockpaymentservice->expects($this->once()) - >method('checkstatus') ->will($this->returnvalue('success')); $result = $this->transaction->pay($orderid); $this->assertequals('success', $result, 'Payment for order 123 should always succeed'); //...

Database Double Gevoelig voor veranderingen Langzaam Indien mogelijk vermijden

Database test opzetten <?php //..Includes class TransactionLogTest extends PHPUnit_Extensions_Database_TestCase /** * REQUIRED * Get the connection for the database setup/teardown. * * @return Database connection. */ protected function getconnection() return $this->createdefaultdbconnection ( $this->pdo, 'shoptest' ); /** * REQUIRED Get the default dataset for * * @return XML dataset */ protected function getdataset() return $this->createflatxmldataset( dirname( FILE ). '/_files/orderlog-seed.xml' ); //...

DB test opzetten (2) Eenvoudige mini test-database Orderlog tabel met orderid, status en een timestamp <?xml version="1.0" encoding="utf-8"?> <dataset> <orderlog orderid="1" status="success" ordertime="2008-10-05 12:35"/> </dataset>

DB test opzetten (3) <?php class transactionlogtest extends PHPUnit_Extensions_Database_TestCase /*... */ /** * OPTIONAL: Truncate everything before inserting. * This is actually the default. */ protected function getsetupoperation() return $this->getoperations()->clean_insert(); /** * OPTIONAL:Truncate all tables after running a test. */ protected function getteardownoperation() return $this->getoperations()->truncate(); /*... */

Databases testen <?php class Transaction //... // PDO database connection protected $pdo; //... public function logorder($orderid, $status) = $this->pdo->prepare( "INSERT INTO orderlog (orderid, status) VALUES (:orderid, :status)" ); if ($stmt->execute( array('orderid'=>$orderid, 'status' => $status ) ) === false) return false; return true; stmt$

DB test opzetten (4a) Na het toevoegen verwacht ik: <?xml version="1.0" encoding="utf-8"?> <dataset> <orderlog orderid="1" status="success" ordertime="2008-10-05 12:35"/> <orderlog orderid="4" status="success" ordertime="2008-10-23 12:36"/> </dataset>

Databases testen (2) <?php //... class TransactionLogTest extends PHPUnit_Extensions_Database_TestCase public function testlogorder() $expecteddataset = $this->createflatxmldataset( dirname( FILE ). '/_files/orderlog-after-add.xml' ); $this->transaction->logorder(4,'success'); $actualdataset = $this->getconnection ()->createdataset (); $this->assertdatasetsequal ($expecteddataset, $actualdataset, 'Add did not show up' );

DB test opzetten (4b) Timestamps zijn niet te voorspellen, die zou ik liever niet terug willen zien in de 'verwachte' data: <?xml version="1.0" encoding="utf-8"?> <dataset> <orderlog orderid="1" status="success"/> <orderlog orderid="4" status="success"/> </dataset>

Databases testen (3) <?php //... /** * Transaction test case. */ class TransactionLogTest extends PHPUnit_Extensions_Database_TestCase //... public function testlogorderfiltered() $expecteddataset = $this->createflatxmldataset( dirname( FILE ). '/_files/orderlog-after-add-filtered.xml' ); $this->transaction->logorder(4,'success'); $actualdataset = new PHPUnit_Extensions_Database_DataSet_DataSetFilter( $this->getconnection()->createdataset(array('orderlog')), array('orderlog'=>'ordertime') -this$ ;( >assertdatasetsequal ( $expecteddataset, $actualdataset, 'Add did not show up' );

PHPUnit en Selenium (RC) Selenium is een Firefox plugin voor het testen van web front-ends. Selenium IDE is een recorder waarmee je acties kunt vastleggen op een website, gebaseerd op het DOM van de pagina's. Selenium RC is een java server die met browsers (FF, IE, Safari, Chrome?) can communiceren. Wanneer je Java hebt, gewoon unzippen in een handige directory. http://selenium.openqa.org/ http://selenium-rc.openqa.org/

PHPUnit en Selenium RC <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>test Title</title> </head> <body> <p>selenium Test Testpage.</p> <div id='requireddiv'>important div</div> </body> </html>

PHPUnit en Selenium RC <?php require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class seleniumtestcase extends PHPUnit_Extensions_SeleniumTestCase function setup() $this->sethost("localhost"); $this->setbrowser("*iexplore"); $this->setbrowserurl("http://uidp/"); function testmytestcase() $this->open("/html"); $this->asserttitleequals('test Title'); $this->asserttextpresent('selenium Test Testpage.'); $this->assertelementpresent("//div[@id='requireddiv']");?>