Symfony - Unit Testing

Il test unitario è essenziale per lo sviluppo continuo in progetti di grandi dimensioni. I test unitari testeranno automaticamente i componenti dell'applicazione e ti avviseranno quando qualcosa non funziona. Gli unit test possono essere eseguiti manualmente, ma spesso sono automatizzati.

PHPUnit

Il framework Symfony si integra con il framework di test di unità PHPUnit. Per scrivere uno unit test per il framework Symfony, abbiamo bisogno di impostare PHPUnit. Se PHPUnit non è installato, scaricalo e installalo. Se è installato correttamente, vedrai la seguente risposta.

phpunit 
PHPUnit 5.1.3 by Sebastian Bergmann and contributors

Test unitario

Uno unit test è un test contro una singola classe PHP, chiamata anche come unità.

Crea una classe Student nella directory Libs / dell'AppBundle. Si trova in“src/AppBundle/Libs/Student.php”.

Student.php

namespace AppBundle\Libs; 

class Student { 
   public function show($name) { 
      return $name. “ , Student name is tested!”; 
   } 
}

Ora, crea un file StudentTest nella directory "tests / AppBundle / Libs".

StudentTest.php

namespace Tests\AppBundle\Libs; 
use AppBundle\Libs\Student;  

class StudentTest extends \PHPUnit_Framework_TestCase { 
   public function testShow() { 
      $stud = new Student(); 
      $assign = $stud->show(‘stud1’); 
      $check = “stud1 , Student name is tested!”; 
      $this->assertEquals($check, $assign); 
   } 
}

Esegui test

Per eseguire il test nella directory, utilizzare il seguente comando.

$ phpunit

Dopo aver eseguito il comando precedente, vedrai la seguente risposta.

PHPUnit 5.1.3 by Sebastian Bergmann and contributors.  
Usage: phpunit [options] UnitTest [UnitTest.php] 
   phpunit [options] <directory>  
Code Coverage Options:  
   --coverage-clover <file>  Generate code coverage report in Clover XML format. 
   --coverage-crap4j <file>  Generate code coverage report in Crap4J XML format. 
   --coverage-html <dir>     Generate code coverage report in HTML format.

Ora, esegui i test nella directory Libs come segue.

$ phpunit tests/AppBundle/Libs

Risultato

Time: 26 ms, Memory: 4.00Mb 
OK (1 test, 1 assertion)