SlideShare ist ein Scribd-Unternehmen logo
1 von 71
Downloaden Sie, um offline zu lesen
E NO SÉTIMO DIA ELE
                         CRIOU TESTES
         TDD e o papel de testes no desenvolvimento de aplicações




                                                Rafael Dohms
                                                rafael@rafaeldohms.com.br
Friday, November 27, 2009
Aviso

                 As referências e opiniões religiosas apresentadas
                 nesta palestra não refletem a opinião do autor, e
                    são apresentadas puramente com intuito de
                  ilustrar pontos-chave de forma descontraída e
                                    humorística.




Friday, November 27, 2009
A CRIAÇÃO DO MUNDO
                    do ponto de vista do desenvolvimento de software

Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
@OCriador




Friday, November 27, 2009
@OCriador
        * Adão has joined #earth
                                   Adão
        * Eva has joined #earth
                                   Eva




Friday, November 27, 2009
@OCriador
        * Adão has joined #earth
                                    Adão
        * Eva has joined #earth
                                    Eva
        Adão: Agora vou apavorar!
        Eva: Primeiro post!
        Eva: ah droga!
        Eva: Olha! uma maçã!




Friday, November 27, 2009
@OCriador
        * Adão has joined #earth
                                    Adão
        * Eva has joined #earth
                                    Eva
        Adão: Agora vou apavorar!
        Eva: Primeiro post!
        Eva: ah droga!
        Eva: Olha! uma maçã!
        > Eva morde a maçã
        OCriador: eu avisei!




Friday, November 27, 2009
@OCriador
        * Adão has joined #earth
                                                 Adão
        * Eva has joined #earth
                                                 Eva
        Adão: Agora vou apavorar!
        Eva: Primeiro post!
        Eva: ah droga!
        Eva: Olha! uma maçã!
        > Eva morde a maçã
        OCriador: eu avisei!
        OCriador kicks Eva
        OCriador kicks Adão
        OCriador adds ban on *@earth on #earth




Friday, November 27, 2009
QUEM É RAFAEL DOHMS?
    Rafael Dohms é graduado Engenheiro da Computação pelo
    UniCEUB. Tem 9 anos de experiência no mercado PHP e atualmente
    ocupa o cargo de Desenvolvedor Sênior e Especialista em
    PHP na empresa sul-africana SWAT/MIH. É certificado ZCE PHP5.

   Grande agitador da comunidade PHP é co-fundador do PHPDF e
   atual coordenador do PHPSP. Contribui ativamente na área de
   testes do PHP e é Host do PHPSPCast, o primeiro podcast
   sobre PHP do Brazil.




Friday, November 27, 2009
Sebastian
                                                                  Bergmann




                                  TESTES
                  porque você precisa deles, mas ainda não sabe

Friday, November 27, 2009
PRÓS
    • “Simulação”

         • Facilidade  de testar funções sem precisar preencher
             formulários, criar usuários
         • Tudo             fica centralizado no teste e é feito apenas uma vez
    • “Certeza”

         • Testes  podem simular todas situações possíveis e garantir
             que seu código funciona como esperado
    • “Garantia”

         • Com     um sistema coberto de testes você tem certeza que
             sua alteração não vai quebrar outra área do sistema

Friday, November 27, 2009
CONS

    • Tempo

         • Embora você gaste mais tempo criando testes, você ganha
             tempo durante as simulações e na manutenção
    • Gerência

         • Convencer    os responsáveis pelo projeto de que testes irão
             trazer lucro é geralmente complicado




Friday, November 27, 2009
CADA SITUAÇÃO, UMA FERRAMENTA



         Frontend           Backend   PHP


       Selenium
           +                PHPUnit   PHPT
       PHPUnit




Friday, November 27, 2009
skoop @flickr




                            ESCREVENDO TESTES
                            quando você começar, nunca mais vai parar

Friday, November 27, 2009
MANOWARS!


    • Sistema               de Batalhas
    • Garantindo               o elemento aleatório
         • Ataque: Fixo           + Random
         • Defesa: Fixo           + Random
         • Damage: Atk/Def                * Random




Friday, November 27, 2009
Mano Gil pronto para combater.
 > Atk: 10 / Def: 8
 Mano Brown pronto para combater.
 > Atk: 11 / Def: 9
                                    UMA BATALHA!
 Round 1
 Fight!
 Gil took 3 damage from Brown
 Gil did 13 damage on Brown
 Gil did 10 damage on Brown
 Gil did 1 damage on Brown
 Gil took 12 damage from Brown
 Gil did 13 damage on Brown
 Gil did 2 damage on Brown
 Gil did 0 damage on Brown
 Gil took 7 damage from Brown
 Gil did 13 damage on Brown
 Gil did 10 damage on Brown
 Gil did 0 damage on Brown
 Gil took 13 damage from Brown
 Gil took 1 damage from Brown
 Gil took 10 damage from Brown
 Gil took 10 damage from Brown
 Gil did 14 damage on Brown
 Gil took 9 damage from Brown
 Gil took 7 damage from Brown
 Gil did 6 damage on Brown
 Gil did 8 damage on Brown
 Gil did 2 damage on Brown
 Gil did 12 damage on Brown
 Gil won!

Friday, November 27, 2009
MW_MANO
                            Vamos ver de perto o código

Friday, November 27, 2009
O QUE TESTAR?
    1.O construtor esta definindo as variáveis?
    2.O health (saúde) está em 100 quando damos reset?
    3.Quando ele se machuca, o health diminui?
    4.Quando vivo, ele diz “tô vivo”?
    5.Quando morto, ele morre?
    6.Ele se defende com o valor de defesa esperado?
    7.Ele ganha bonus de defesa?
    8.Qual o resultado de um ataque (sem bônus), quando:
         8.1.Atk > Def
         8.2.Def > Atk
         8.3.Atk = Def

Friday, November 27, 2009
RAIO-X DE UMA SUITE DE TESTES
        PHPUnit_Framework_TestSuite


                AllTests




Friday, November 27, 2009
RAIO-X DE UMA SUITE DE TESTES
        PHPUnit_Framework_TestSuite


                AllTests
                               PHPUnit_Framework_TestCase


                                  ClassXTest
                               PHPUnit_Framework_TestCase


                                  ClassXTest
                               PHPUnit_Framework_TestCase


                                  ClassXTest




Friday, November 27, 2009
RAIO-X DE UMA SUITE DE TESTES
        PHPUnit_Framework_TestSuite


                AllTests
                               PHPUnit_Framework_TestCase
                                                            testX
                                  ClassXTest
                                                            ...
                                                            testY

                               PHPUnit_Framework_TestCase
                                                            testX
                                  ClassXTest
                                                            ...
                                                            testY


                               PHPUnit_Framework_TestCase
                                                            testX
                                  ClassXTest
                                                            ...
                                                            testY




Friday, November 27, 2009
RAIO-X DE UMA SUITE DE TESTES
        PHPUnit_Framework_TestSuite
                                         SetUp
                AllTests               TearDown

                               PHPUnit_Framework_TestCase

                                                             SetUp     testX
                                  ClassXTest
                                                                       ...
                                                            TearDown   testY

                               PHPUnit_Framework_TestCase
                                                             SetUp     testX
                                  ClassXTest
                                                                       ...
                                                            TearDown   testY


                               PHPUnit_Framework_TestCase
                                                             SetUp     testX
                                  ClassXTest
                                                                       ...
                                                            TearDown   testY




Friday, November 27, 2009
EXECUÇÃO DA SUITE
                                   SetUp




                                   SetUp
                                             Para cada teste
                                  TearDown




                                   SetUp
                                             Para cada teste
                                  TearDown




                                   SetUp
                                             Para cada teste
                                  TearDown




                                  TearDown


Friday, November 27, 2009
ISOLAMENTO

    • Mantenha                seus testes isolados
    • Nunca                  rode testes no servidor de produção!
    • Soluções

         • Crie             uma base separada
         • Use          pastas separadas para arquivos
         • Sempre             destrua tudo que seu teste construiu



Friday, November 27, 2009
ESQUADRÃO LIMPEZA
  Limpe tudo o que seu teste criar!
           class CleanUpTest extends PHPUnit_Framework_TestCase
           {
               private $file = "/tmp/file";

                    protected function setUp()
                    {
                        parent::setUp();
                    }

                    protected function tearDown()
                    {
                        unlink($this->file);
                        parent::tearDown();
                    }

                    public function testFile()
                    {
                        file_put_contents($this->file);
                    }
Friday, November 27, 2009
ESQUADRÃO LIMPEZA
  Limpe tudo o que seu teste criar!
           class CleanUpTest extends PHPUnit_Framework_TestCase
           {
               private $file = "/tmp/file";

                    protected function setUp()
                    {
                        parent::setUp();
                    }

                    protected function tearDown()
                    {
                        unlink($this->file);
                        parent::tearDown();
                    }

                    public function testFile()               Everything
                    {                                       must be clean!
                        file_put_contents($this->file);
                    }
Friday, November 27, 2009
ESQUADRÃO LIMPEZA
  Limpe tudo o que seu teste criar!
           class CleanUpTest extends PHPUnit_Framework_TestCase
           {
               private $file = "/tmp/file";

                    protected function setUp()
                    {
                        parent::setUp();
                    }

                    protected function tearDown()
                    {                                             Arquivos, Banco de
                        unlink($this->file);                         Dados, etc...
                        parent::tearDown();
                    }

                    public function testFile()               Everything
                    {                                       must be clean!
                        file_put_contents($this->file);
                    }
Friday, November 27, 2009
TIPOS
    • Teste                 Unitário
         • Pequeno            e pontual
         • Geralmente            testa a entrada/saída de uma função
    • Teste                 Funcional
         • Verifica           a funcionalidade de interfaces
    • End-to-End

         • Verifica           o processo do início ao fim
         • Analisa           o fluxo de sua aplicação


Friday, November 27, 2009
TESTANDO OS BÁSICOS


    • Estrutura             da Suite
         • AllTests.php

         • MW_Mano

              • Testes       do 1 ao 6




Friday, November 27, 2009
public function attack(MW_Mano $victim)
    {
        $atk = $this->getAtk() + trim(file_get_contents('URL'));
        $def = $victim->defend();

             $dmgMultiplier = (trim(file_get_contents('URL')))/100;

             if ($atk > $def){
                 $dmg = round($atk * $dmgMultiplier);
                 $victim->hurt( $dmg );
                 $action = "%s did %d damage on %s";
             }else{
                 $dmg = round($def * $dmgMultiplier);
                 $this->hurt( $dmg );
                 $action = "%s took %d damage from %s";

             }

             return sprintf($action, $this->getName(), $dmg, $victim->getName());
    }



 Para Facilitar leitura:
 [URL] => http://www.random.org/integers/?num=1&min=0&max=100&col=1&base=10&format=plain&rnd=new

Friday, November 27, 2009
CÓDIGO DEINTESTÁVEL

    • Singletons

         • MyClass::getInstance();

    • Dependências

         • SO: exec(‘ls                -la’);
         • Recursos           externos: APIs, File System
    • Métodos               Privados
         • private              method fazTudo(){...}


Friday, November 27, 2009
public function attack(MW_Mano $victim)
 {
     $atk = $this->getAtk() + $this->getRandom();
     $def = $victim->defend();

        $dmgMultiplier = $this->getRandom(1,100)/100;

        if ($atk > $def){
            $dmg = round($atk * $dmgMultiplier);
            $victim->hurt( $dmg );
            $action = "%s did %d damage on %s";
        }else{
            $dmg = round($def * $dmgMultiplier);
            $this->hurt( $dmg );
            $action = "%s took %d damage from %s";

        }

        return sprintf($action, $this->getName(), $dmg, $victim->getName());
 }

 public function getRandom($min = 1, $max = 10)
 {
     return trim(file_get_contents('http://www.random.org/integers/?num=1&min='.
 $min.'&max='.$max.'&col=1&base=10&format=plain&rnd=new'));
 }




Friday, November 27, 2009
NINJA TESTING

    • Porque, às            vezes, os testes precisam de dublês
         • Dummy

         • Fake

         • Stub

         • Spy

         • Mock




Friday, November 27, 2009
RANDOM SEM O RANDOM
 public function testDefendWithoutLuck()
 {
     //Obter Mock
     $manoMock = $this->getMock('MW_Mano',array('getRandom'),
 array('John'));
     //Definir que o objeto retorne zero.
     $manoMock->expects($this->any())
              ->method('getRandom')
              ->will($this->returnValue(0));

            //Definir defesa
            $manoMock->setDef(5);

            //Verificar que defesa nao se altera
            $this->assertEquals(5, $manoMock->defend());
 }

Friday, November 27, 2009
DATA PROVIDERS



    •1       teste, muitos dados
    • Análise               completa de diferentes quadros




Friday, November 27, 2009
CODE COVERAGE
    • phpunit.xml

    <phpunit colors="true" verbose="true">

        <logging>
            <log type="coverage-html" target="_reports" charset="UTF-8" yui="true"
    highlight="true" />
        </logging>

           <filter>
             <blacklist>
               <directory suffix=".php">../libs/Zend</directory>
             </blacklist>
             <whitelist>
               <directory suffix=".php">../libs/MW</directory>
             </whitelist>
           </filter>

    </phpunit>




Friday, November 27, 2009
Friday, November 27, 2009
Test Driven Development




                                           TDD
                            Não é sobre testes, é sobre especificações

Friday, November 27, 2009
“TDD é uma forma de projetar software,
      não apenas uma forma de testar software.”
                            Sebastian Bergmann - criador do PHPUnit




        “It's about figuring out what you are trying
        to do before you run off half-cocked to try
                         to do it.”
                              Dave Astels - autor de livros sobre TDD




Friday, November 27, 2009
TDD


    • Escrever   testes que definem o comportamento de sua
        aplicação antes de escrever código.
    • Testar                comportamento, não apenas funcionamento
    • Especificar               e não apenas validar




Friday, November 27, 2009
Especificação          Análise   Codificação




       Manutenção           Deploy      Testes




     CICLO DE DESENVOLVIMENTO
                            sem TDD

Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Codificação




Friday, November 27, 2009
Especificação           Análise   Codificação




       Manutenção            Deploy      Testes




     CICLO DE DESENVOLVIMENTO
                            sem TDD

Friday, November 27, 2009
Especificação           Análise     Testes




       Manutenção            Deploy    Codificação




     CICLO DE DESENVOLVIMENTO
                            sem TDD

Friday, November 27, 2009
Especificação           Análise     Testes




       Manutenção            Deploy    Codificação




     CICLO DE DESENVOLVIMENTO
                            sem TDD

Friday, November 27, 2009
Testes

              O que desejamos que <método> faça?
              Massa de dados para Teste




      Codificação

              Como <método> fará o que precisa?

             Sem formulários, teste direto o backend com os dados


Friday, November 27, 2009
Especificação             Análise      Testes




       Manutenção              Deploy     Codificação




     CICLO DE DESENVOLVIMENTO
                            sem com TDD

Friday, November 27, 2009
Manutenção


    • Processo               de correção de bugs

         • Identificar          erro

         • Escrever           teste que cause falha

         • Corrigir          código

         • Rodar            teste novamente

         • Verificar          que o teste passou

Friday, November 27, 2009
RINSE AND REPEAT
                 Automatize seus testes e garanta qualidade da equipe

Friday, November 27, 2009
CONTINUOS INTEGRATION

    • “Integração           contínua”
         • Processo         automatizado
         • Executado         após cada commit
         • Identifica        falhas
         • Identifica        culpados
         • Controla         qualidade



Friday, November 27, 2009
Friday, November 27, 2009
FERRAMENTAS

    • phpUnderControl

         • baseado           no CruiseControl
         • Versão           atual já formata:
              • Resultados        de Testes
              • PHP         Code Sniffer
              • Code         Coverage
              • phpDoc



Friday, November 27, 2009
Friday, November 27, 2009
Friday, November 27, 2009
DÚVIDAS?
Friday, November 27, 2009
www.rafaeldohms.com.br
                                        rafael@rafaeldohms.com.br



                               Obrigado!




                 Avalie essa palestra: http://joind.in/1168
Friday, November 27, 2009

Weitere ähnliche Inhalte

Andere mochten auch

Trilhando o Caminho PHP - PHPConf2008
Trilhando o Caminho PHP - PHPConf2008Trilhando o Caminho PHP - PHPConf2008
Trilhando o Caminho PHP - PHPConf2008Rafael Dohms
 
PHP e AJAX: do Request ao Framework
PHP e AJAX: do Request ao FrameworkPHP e AJAX: do Request ao Framework
PHP e AJAX: do Request ao FrameworkRafael Dohms
 
PHP Community in Brazil
PHP Community in BrazilPHP Community in Brazil
PHP Community in BrazilRafael Dohms
 
PHPSP TestFest 2009
PHPSP TestFest 2009PHPSP TestFest 2009
PHPSP TestFest 2009Rafael Dohms
 
Despertando para o PHP
Despertando para o PHPDespertando para o PHP
Despertando para o PHPRafael Dohms
 
Trilhando o caminho PHP
Trilhando o caminho PHPTrilhando o caminho PHP
Trilhando o caminho PHPRafael Dohms
 
Annotating with Annotations - DPC UnCon
Annotating with Annotations - DPC UnConAnnotating with Annotations - DPC UnCon
Annotating with Annotations - DPC UnConRafael Dohms
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Writing Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtWriting Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtRafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16Rafael Dohms
 

Andere mochten auch (10)

Trilhando o Caminho PHP - PHPConf2008
Trilhando o Caminho PHP - PHPConf2008Trilhando o Caminho PHP - PHPConf2008
Trilhando o Caminho PHP - PHPConf2008
 
PHP e AJAX: do Request ao Framework
PHP e AJAX: do Request ao FrameworkPHP e AJAX: do Request ao Framework
PHP e AJAX: do Request ao Framework
 
PHP Community in Brazil
PHP Community in BrazilPHP Community in Brazil
PHP Community in Brazil
 
PHPSP TestFest 2009
PHPSP TestFest 2009PHPSP TestFest 2009
PHPSP TestFest 2009
 
Despertando para o PHP
Despertando para o PHPDespertando para o PHP
Despertando para o PHP
 
Trilhando o caminho PHP
Trilhando o caminho PHPTrilhando o caminho PHP
Trilhando o caminho PHP
 
Annotating with Annotations - DPC UnCon
Annotating with Annotations - DPC UnConAnnotating with Annotations - DPC UnCon
Annotating with Annotations - DPC UnCon
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Writing Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, UtrechtWriting Code That Lasts - #Magento2Seminar, Utrecht
Writing Code That Lasts - #Magento2Seminar, Utrecht
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
“Writing code that lasts” … or writing code you won’t hate tomorrow. - #PHPSRB16
 

Ähnlich wie E no Sétimo dia ele escreveu testes

Tdd em django sem desculpas versao final
Tdd em django sem desculpas versao finalTdd em django sem desculpas versao final
Tdd em django sem desculpas versao finalAdriano Petrich
 
Introducao ao sistema de gerenciamento de conteúdo Plone
Introducao ao sistema de gerenciamento de conteúdo PloneIntroducao ao sistema de gerenciamento de conteúdo Plone
Introducao ao sistema de gerenciamento de conteúdo PloneFabiano Weimar
 
PHP, Gearman e Memcache
PHP, Gearman e MemcachePHP, Gearman e Memcache
PHP, Gearman e MemcacheAndre Golvea
 
TDD com LEGO #PHPExperience2016
TDD com LEGO #PHPExperience2016TDD com LEGO #PHPExperience2016
TDD com LEGO #PHPExperience2016Simone Pittner
 
PHP Experience 2016 - [Workshop] Agile: Test Driven Development
PHP Experience 2016 - [Workshop] Agile: Test Driven DevelopmentPHP Experience 2016 - [Workshop] Agile: Test Driven Development
PHP Experience 2016 - [Workshop] Agile: Test Driven DevelopmentiMasters
 
Test Driven Development - Trabalhe tranquilo e maximize sua produtividade
Test Driven Development - Trabalhe tranquilo e maximize sua produtividadeTest Driven Development - Trabalhe tranquilo e maximize sua produtividade
Test Driven Development - Trabalhe tranquilo e maximize sua produtividadeFlávio Ribeiro
 
Hardening linux
Hardening linuxHardening linux
Hardening linuxhdoria
 
Coding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentCoding Dojo e Test Driven Development
Coding Dojo e Test Driven Developmentpugpe
 
Coding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentCoding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentRodrigo Alves Vieira
 

Ähnlich wie E no Sétimo dia ele escreveu testes (12)

Tdd em django sem desculpas versao final
Tdd em django sem desculpas versao finalTdd em django sem desculpas versao final
Tdd em django sem desculpas versao final
 
Introducao ao sistema de gerenciamento de conteúdo Plone
Introducao ao sistema de gerenciamento de conteúdo PloneIntroducao ao sistema de gerenciamento de conteúdo Plone
Introducao ao sistema de gerenciamento de conteúdo Plone
 
PHP, Gearman e Memcache
PHP, Gearman e MemcachePHP, Gearman e Memcache
PHP, Gearman e Memcache
 
Python com TDD
Python com TDDPython com TDD
Python com TDD
 
TDD com LEGO #PHPExperience2016
TDD com LEGO #PHPExperience2016TDD com LEGO #PHPExperience2016
TDD com LEGO #PHPExperience2016
 
PHP Experience 2016 - [Workshop] Agile: Test Driven Development
PHP Experience 2016 - [Workshop] Agile: Test Driven DevelopmentPHP Experience 2016 - [Workshop] Agile: Test Driven Development
PHP Experience 2016 - [Workshop] Agile: Test Driven Development
 
Test Driven Development - Trabalhe tranquilo e maximize sua produtividade
Test Driven Development - Trabalhe tranquilo e maximize sua produtividadeTest Driven Development - Trabalhe tranquilo e maximize sua produtividade
Test Driven Development - Trabalhe tranquilo e maximize sua produtividade
 
TDD com Python
TDD com PythonTDD com Python
TDD com Python
 
Flisol 2012
Flisol 2012Flisol 2012
Flisol 2012
 
Hardening linux
Hardening linuxHardening linux
Hardening linux
 
Coding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentCoding Dojo e Test Driven Development
Coding Dojo e Test Driven Development
 
Coding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentCoding Dojo e Test Driven Development
Coding Dojo e Test Driven Development
 

Mehr von Rafael Dohms

The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024Rafael Dohms
 
Application Metrics - IPC2023
Application Metrics - IPC2023Application Metrics - IPC2023
Application Metrics - IPC2023Rafael Dohms
 
How'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsHow'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsRafael Dohms
 
Architectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRArchitectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRRafael Dohms
 
Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Rafael Dohms
 
Application metrics - Confoo 2019
Application metrics - Confoo 2019Application metrics - Confoo 2019
Application metrics - Confoo 2019Rafael Dohms
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Rafael Dohms
 
Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Rafael Dohms
 
Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...Rafael Dohms
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHPRafael Dohms
 
Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Rafael Dohms
 
Composer the Right Way - MM16NL
Composer the Right Way - MM16NLComposer the Right Way - MM16NL
Composer the Right Way - MM16NLRafael Dohms
 
Composer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNComposer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNRafael Dohms
 
Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 
A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.Rafael Dohms
 

Mehr von Rafael Dohms (20)

The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024The Individual Contributor Path - DPC2024
The Individual Contributor Path - DPC2024
 
Application Metrics - IPC2023
Application Metrics - IPC2023Application Metrics - IPC2023
Application Metrics - IPC2023
 
How'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision RecordsHow'd we get here? A guide to Architectural Decision Records
How'd we get here? A guide to Architectural Decision Records
 
Architectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBRArchitectural Decision Records - PHPConfBR
Architectural Decision Records - PHPConfBR
 
Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)Application Metrics (with Prometheus examples)
Application Metrics (with Prometheus examples)
 
Application metrics - Confoo 2019
Application metrics - Confoo 2019Application metrics - Confoo 2019
Application metrics - Confoo 2019
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18
 
Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18Application Metrics (with Prometheus examples) #PHPDD18
Application Metrics (with Prometheus examples) #PHPDD18
 
Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18Application metrics with Prometheus - DPC18
Application metrics with Prometheus - DPC18
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
 
Composer The Right Way - 010PHP
Composer The Right Way - 010PHPComposer The Right Way - 010PHP
Composer The Right Way - 010PHP
 
Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16Composer the Right Way - PHPSRB16
Composer the Right Way - PHPSRB16
 
Composer the Right Way - MM16NL
Composer the Right Way - MM16NLComposer the Right Way - MM16NL
Composer the Right Way - MM16NL
 
Composer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRNComposer The Right Way - PHPUGMRN
Composer The Right Way - PHPUGMRN
 
Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16Composer the Right Way - PHPBNL16
Composer the Right Way - PHPBNL16
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 
A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015A Journey into your Lizard Brain - PHP Conference Brasil 2015
A Journey into your Lizard Brain - PHP Conference Brasil 2015
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 
“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.“Writing code that lasts” … or writing code you won’t hate tomorrow.
“Writing code that lasts” … or writing code you won’t hate tomorrow.
 

E no Sétimo dia ele escreveu testes

  • 1. E NO SÉTIMO DIA ELE CRIOU TESTES TDD e o papel de testes no desenvolvimento de aplicações Rafael Dohms rafael@rafaeldohms.com.br Friday, November 27, 2009
  • 2. Aviso As referências e opiniões religiosas apresentadas nesta palestra não refletem a opinião do autor, e são apresentadas puramente com intuito de ilustrar pontos-chave de forma descontraída e humorística. Friday, November 27, 2009
  • 3. A CRIAÇÃO DO MUNDO do ponto de vista do desenvolvimento de software Friday, November 27, 2009
  • 13. @OCriador * Adão has joined #earth Adão * Eva has joined #earth Eva Friday, November 27, 2009
  • 14. @OCriador * Adão has joined #earth Adão * Eva has joined #earth Eva Adão: Agora vou apavorar! Eva: Primeiro post! Eva: ah droga! Eva: Olha! uma maçã! Friday, November 27, 2009
  • 15. @OCriador * Adão has joined #earth Adão * Eva has joined #earth Eva Adão: Agora vou apavorar! Eva: Primeiro post! Eva: ah droga! Eva: Olha! uma maçã! > Eva morde a maçã OCriador: eu avisei! Friday, November 27, 2009
  • 16. @OCriador * Adão has joined #earth Adão * Eva has joined #earth Eva Adão: Agora vou apavorar! Eva: Primeiro post! Eva: ah droga! Eva: Olha! uma maçã! > Eva morde a maçã OCriador: eu avisei! OCriador kicks Eva OCriador kicks Adão OCriador adds ban on *@earth on #earth Friday, November 27, 2009
  • 17. QUEM É RAFAEL DOHMS? Rafael Dohms é graduado Engenheiro da Computação pelo UniCEUB. Tem 9 anos de experiência no mercado PHP e atualmente ocupa o cargo de Desenvolvedor Sênior e Especialista em PHP na empresa sul-africana SWAT/MIH. É certificado ZCE PHP5. Grande agitador da comunidade PHP é co-fundador do PHPDF e atual coordenador do PHPSP. Contribui ativamente na área de testes do PHP e é Host do PHPSPCast, o primeiro podcast sobre PHP do Brazil. Friday, November 27, 2009
  • 18. Sebastian Bergmann TESTES porque você precisa deles, mas ainda não sabe Friday, November 27, 2009
  • 19. PRÓS • “Simulação” • Facilidade de testar funções sem precisar preencher formulários, criar usuários • Tudo fica centralizado no teste e é feito apenas uma vez • “Certeza” • Testes podem simular todas situações possíveis e garantir que seu código funciona como esperado • “Garantia” • Com um sistema coberto de testes você tem certeza que sua alteração não vai quebrar outra área do sistema Friday, November 27, 2009
  • 20. CONS • Tempo • Embora você gaste mais tempo criando testes, você ganha tempo durante as simulações e na manutenção • Gerência • Convencer os responsáveis pelo projeto de que testes irão trazer lucro é geralmente complicado Friday, November 27, 2009
  • 21. CADA SITUAÇÃO, UMA FERRAMENTA Frontend Backend PHP Selenium + PHPUnit PHPT PHPUnit Friday, November 27, 2009
  • 22. skoop @flickr ESCREVENDO TESTES quando você começar, nunca mais vai parar Friday, November 27, 2009
  • 23. MANOWARS! • Sistema de Batalhas • Garantindo o elemento aleatório • Ataque: Fixo + Random • Defesa: Fixo + Random • Damage: Atk/Def * Random Friday, November 27, 2009
  • 24. Mano Gil pronto para combater. > Atk: 10 / Def: 8 Mano Brown pronto para combater. > Atk: 11 / Def: 9 UMA BATALHA! Round 1 Fight! Gil took 3 damage from Brown Gil did 13 damage on Brown Gil did 10 damage on Brown Gil did 1 damage on Brown Gil took 12 damage from Brown Gil did 13 damage on Brown Gil did 2 damage on Brown Gil did 0 damage on Brown Gil took 7 damage from Brown Gil did 13 damage on Brown Gil did 10 damage on Brown Gil did 0 damage on Brown Gil took 13 damage from Brown Gil took 1 damage from Brown Gil took 10 damage from Brown Gil took 10 damage from Brown Gil did 14 damage on Brown Gil took 9 damage from Brown Gil took 7 damage from Brown Gil did 6 damage on Brown Gil did 8 damage on Brown Gil did 2 damage on Brown Gil did 12 damage on Brown Gil won! Friday, November 27, 2009
  • 25. MW_MANO Vamos ver de perto o código Friday, November 27, 2009
  • 26. O QUE TESTAR? 1.O construtor esta definindo as variáveis? 2.O health (saúde) está em 100 quando damos reset? 3.Quando ele se machuca, o health diminui? 4.Quando vivo, ele diz “tô vivo”? 5.Quando morto, ele morre? 6.Ele se defende com o valor de defesa esperado? 7.Ele ganha bonus de defesa? 8.Qual o resultado de um ataque (sem bônus), quando: 8.1.Atk > Def 8.2.Def > Atk 8.3.Atk = Def Friday, November 27, 2009
  • 27. RAIO-X DE UMA SUITE DE TESTES PHPUnit_Framework_TestSuite AllTests Friday, November 27, 2009
  • 28. RAIO-X DE UMA SUITE DE TESTES PHPUnit_Framework_TestSuite AllTests PHPUnit_Framework_TestCase ClassXTest PHPUnit_Framework_TestCase ClassXTest PHPUnit_Framework_TestCase ClassXTest Friday, November 27, 2009
  • 29. RAIO-X DE UMA SUITE DE TESTES PHPUnit_Framework_TestSuite AllTests PHPUnit_Framework_TestCase testX ClassXTest ... testY PHPUnit_Framework_TestCase testX ClassXTest ... testY PHPUnit_Framework_TestCase testX ClassXTest ... testY Friday, November 27, 2009
  • 30. RAIO-X DE UMA SUITE DE TESTES PHPUnit_Framework_TestSuite SetUp AllTests TearDown PHPUnit_Framework_TestCase SetUp testX ClassXTest ... TearDown testY PHPUnit_Framework_TestCase SetUp testX ClassXTest ... TearDown testY PHPUnit_Framework_TestCase SetUp testX ClassXTest ... TearDown testY Friday, November 27, 2009
  • 31. EXECUÇÃO DA SUITE SetUp SetUp Para cada teste TearDown SetUp Para cada teste TearDown SetUp Para cada teste TearDown TearDown Friday, November 27, 2009
  • 32. ISOLAMENTO • Mantenha seus testes isolados • Nunca rode testes no servidor de produção! • Soluções • Crie uma base separada • Use pastas separadas para arquivos • Sempre destrua tudo que seu teste construiu Friday, November 27, 2009
  • 33. ESQUADRÃO LIMPEZA Limpe tudo o que seu teste criar! class CleanUpTest extends PHPUnit_Framework_TestCase { private $file = "/tmp/file"; protected function setUp() { parent::setUp(); } protected function tearDown() { unlink($this->file); parent::tearDown(); } public function testFile() { file_put_contents($this->file); } Friday, November 27, 2009
  • 34. ESQUADRÃO LIMPEZA Limpe tudo o que seu teste criar! class CleanUpTest extends PHPUnit_Framework_TestCase { private $file = "/tmp/file"; protected function setUp() { parent::setUp(); } protected function tearDown() { unlink($this->file); parent::tearDown(); } public function testFile() Everything { must be clean! file_put_contents($this->file); } Friday, November 27, 2009
  • 35. ESQUADRÃO LIMPEZA Limpe tudo o que seu teste criar! class CleanUpTest extends PHPUnit_Framework_TestCase { private $file = "/tmp/file"; protected function setUp() { parent::setUp(); } protected function tearDown() { Arquivos, Banco de unlink($this->file); Dados, etc... parent::tearDown(); } public function testFile() Everything { must be clean! file_put_contents($this->file); } Friday, November 27, 2009
  • 36. TIPOS • Teste Unitário • Pequeno e pontual • Geralmente testa a entrada/saída de uma função • Teste Funcional • Verifica a funcionalidade de interfaces • End-to-End • Verifica o processo do início ao fim • Analisa o fluxo de sua aplicação Friday, November 27, 2009
  • 37. TESTANDO OS BÁSICOS • Estrutura da Suite • AllTests.php • MW_Mano • Testes do 1 ao 6 Friday, November 27, 2009
  • 38. public function attack(MW_Mano $victim) { $atk = $this->getAtk() + trim(file_get_contents('URL')); $def = $victim->defend(); $dmgMultiplier = (trim(file_get_contents('URL')))/100; if ($atk > $def){ $dmg = round($atk * $dmgMultiplier); $victim->hurt( $dmg ); $action = "%s did %d damage on %s"; }else{ $dmg = round($def * $dmgMultiplier); $this->hurt( $dmg ); $action = "%s took %d damage from %s"; } return sprintf($action, $this->getName(), $dmg, $victim->getName()); } Para Facilitar leitura: [URL] => http://www.random.org/integers/?num=1&min=0&max=100&col=1&base=10&format=plain&rnd=new Friday, November 27, 2009
  • 39. CÓDIGO DEINTESTÁVEL • Singletons • MyClass::getInstance(); • Dependências • SO: exec(‘ls -la’); • Recursos externos: APIs, File System • Métodos Privados • private method fazTudo(){...} Friday, November 27, 2009
  • 40. public function attack(MW_Mano $victim) { $atk = $this->getAtk() + $this->getRandom(); $def = $victim->defend(); $dmgMultiplier = $this->getRandom(1,100)/100; if ($atk > $def){ $dmg = round($atk * $dmgMultiplier); $victim->hurt( $dmg ); $action = "%s did %d damage on %s"; }else{ $dmg = round($def * $dmgMultiplier); $this->hurt( $dmg ); $action = "%s took %d damage from %s"; } return sprintf($action, $this->getName(), $dmg, $victim->getName()); } public function getRandom($min = 1, $max = 10) { return trim(file_get_contents('http://www.random.org/integers/?num=1&min='. $min.'&max='.$max.'&col=1&base=10&format=plain&rnd=new')); } Friday, November 27, 2009
  • 41. NINJA TESTING • Porque, às vezes, os testes precisam de dublês • Dummy • Fake • Stub • Spy • Mock Friday, November 27, 2009
  • 42. RANDOM SEM O RANDOM public function testDefendWithoutLuck() { //Obter Mock $manoMock = $this->getMock('MW_Mano',array('getRandom'), array('John')); //Definir que o objeto retorne zero. $manoMock->expects($this->any()) ->method('getRandom') ->will($this->returnValue(0)); //Definir defesa $manoMock->setDef(5); //Verificar que defesa nao se altera $this->assertEquals(5, $manoMock->defend()); } Friday, November 27, 2009
  • 43. DATA PROVIDERS •1 teste, muitos dados • Análise completa de diferentes quadros Friday, November 27, 2009
  • 44. CODE COVERAGE • phpunit.xml <phpunit colors="true" verbose="true"> <logging> <log type="coverage-html" target="_reports" charset="UTF-8" yui="true" highlight="true" /> </logging> <filter> <blacklist> <directory suffix=".php">../libs/Zend</directory> </blacklist> <whitelist> <directory suffix=".php">../libs/MW</directory> </whitelist> </filter> </phpunit> Friday, November 27, 2009
  • 46. Test Driven Development TDD Não é sobre testes, é sobre especificações Friday, November 27, 2009
  • 47. “TDD é uma forma de projetar software, não apenas uma forma de testar software.” Sebastian Bergmann - criador do PHPUnit “It's about figuring out what you are trying to do before you run off half-cocked to try to do it.” Dave Astels - autor de livros sobre TDD Friday, November 27, 2009
  • 48. TDD • Escrever testes que definem o comportamento de sua aplicação antes de escrever código. • Testar comportamento, não apenas funcionamento • Especificar e não apenas validar Friday, November 27, 2009
  • 49. Especificação Análise Codificação Manutenção Deploy Testes CICLO DE DESENVOLVIMENTO sem TDD Friday, November 27, 2009
  • 58. Especificação Análise Codificação Manutenção Deploy Testes CICLO DE DESENVOLVIMENTO sem TDD Friday, November 27, 2009
  • 59. Especificação Análise Testes Manutenção Deploy Codificação CICLO DE DESENVOLVIMENTO sem TDD Friday, November 27, 2009
  • 60. Especificação Análise Testes Manutenção Deploy Codificação CICLO DE DESENVOLVIMENTO sem TDD Friday, November 27, 2009
  • 61. Testes O que desejamos que <método> faça? Massa de dados para Teste Codificação Como <método> fará o que precisa? Sem formulários, teste direto o backend com os dados Friday, November 27, 2009
  • 62. Especificação Análise Testes Manutenção Deploy Codificação CICLO DE DESENVOLVIMENTO sem com TDD Friday, November 27, 2009
  • 63. Manutenção • Processo de correção de bugs • Identificar erro • Escrever teste que cause falha • Corrigir código • Rodar teste novamente • Verificar que o teste passou Friday, November 27, 2009
  • 64. RINSE AND REPEAT Automatize seus testes e garanta qualidade da equipe Friday, November 27, 2009
  • 65. CONTINUOS INTEGRATION • “Integração contínua” • Processo automatizado • Executado após cada commit • Identifica falhas • Identifica culpados • Controla qualidade Friday, November 27, 2009
  • 67. FERRAMENTAS • phpUnderControl • baseado no CruiseControl • Versão atual já formata: • Resultados de Testes • PHP Code Sniffer • Code Coverage • phpDoc Friday, November 27, 2009
  • 71. www.rafaeldohms.com.br rafael@rafaeldohms.com.br Obrigado! Avalie essa palestra: http://joind.in/1168 Friday, November 27, 2009