PHP UnitTesting com SimpleTest

Estou a usar o SimpleTest há já mais de um ano, mas nunca tinha verdadeiramente puxado por ele. Agora, que estou a juntar as peças da minha framework, preciso de actualizar os testes por forma a levar o projecto 100% até o próximo nível: test now, code later.

Neste momento, as classes que constituem o core e a base dos controladores (o C do MVC), estão 100% testadas. Claro que nem todos os testes passam ainda, but that’s not the point here…


$test->addTestCase(new test_OE_Base());
$test->addTestCase(new test_OliveConfig());
$test->addTestCase(new test_OliveMessage());
$test->addTestCase(new test_OliveStorageDefault());
$test->addTestCase(new test_OliveLocatorDefault());
$test->addTestCase(new test_OliveLoaderDefault());
$test->addTestCase(new test_OliveExecutorDefault());
$test->addTestCase(new test_OliveConfiguratorDefault());
$test->addTestCase(new test_OliveConfigurableBase());
$test->addTestCase(new test_OliveComponentBase());
$test->addTestCase(new test_OliveExecutableBase());
$test->addTestCase(new test_OliveModuleBase());
$test->addTestCase(new test_OliveControlBase());
$test->addTestCase(new test_OliveFrameworkBuilderBase());
$test->addTestCase(new test_OliveApplicationFactoryBase());

São já 447 testes e ainda falta testar/escrever todas as componentes de Output (V) e Model (M)… Ah! Recordo-me agora que quando eu era substancialmente mais novo as noitadas de sábado eram substancialmente mais divertidas.

Olive Framework tests with SimpleTest

Acerca do SimpleTest

Quando avaliei as frameworks de teste para PHP escolhi o SimpleTest por implementar todas as features (e mais um par de botas) e, ao mesmo tempo, permitir escrever testes com um código, de facto, muito simples.

Entre outras funcionalidades, o SimpleTest permite gerar Mocks em run-time e configurá-los para agir como actores (retornar valores consoante os argumentos) e críticos (testar chamadas e argumentos). Eis um exemplo:


  /**
   * should call given strategies and return as soon as some strategy returns data
   */
  public function test_load_specific_strategy()
  {
    // create
    $configurator = OliveConfiguratorDefault::instance();

    // create mock strategy
    $strategy1 = new MockOliveConfigStrategy();
    $strategy1->expectNever('load');

    // create mock strategy
    $strategy2 = new MockOliveConfigStrategy();
    $strategy2->expectOnce('load', array($this->_path, $this->_name));
    $strategy2->setReturnValue('load', $this->_data);

    // create mock strategy
    $strategy3 = new MockOliveConfigStrategy();
    $strategy3->expectNever('load');    

    // pass mocks
    $configurator->add_strategy($this->_strategy[0], $strategy1);
    $configurator->add_strategy($this->_strategy[1], $strategy2);
    $configurator->add_strategy($this->_strategy[2], $strategy3);       

    // load with specific strategy
    $data = $configurator->load($this->_path, $this->_name, $this->_strategy[1]);

    // assert data
    $this->assertIdentical($data, $this->_data);
  } 

Ainda mais á frente, permite também fazer Web Testing, scraping, navegação, submissão de forms e autenticações. Digo mais à frente porque, apesar do mecanismo ser claro como a água, ainda não consigo pensar em estratégias eficazes para implementar testes desta natureza. Mas lá chegarei.

Mas o SimpleTest tem outras características de ganhador: está relativamente bem documentado, principalmente com exemplos que te possibilitam estar up and running em menos 10 minutos; tem uma comunidade bastante activa (mailing list); a versão que está cá fora é 1.0.1, ou seja, para lá do Beta; o desenvolvimento está bastante activo e os planos são claros no que toca a levar o SimpleTest ao colo até ao php6.

A versão que eu estou a usar é um pouco antiga e foi hacked para permitir testar se durante a execução dos testes houve ou não output para o browser. Por isso ainda não o actualizei para a última versão e ainda não experimentei o plugin para o Eclipse que promete um nível de integração porreiro com o PDT e o XDebug.

The PHP UnitTesting com SimpleTest by Andrezero, unless otherwise expressly stated, is licensed under a Creative Commons Attribution 2.5 Portugal License.

1 Response to “PHP UnitTesting com SimpleTest”


  1. 1 PHP Screen Scraping

    This unitTesting stuff is great I was first exposed to it in a Design Patterns book I was reading. Very nice for keeping your code stable which I’ve had problems with in the past. Cool stuff thanks for the post.

Leave a Reply







Close
E-mail It
ok