Olá a todos!
Meu nome é Anton e agora (não muito tempo, cerca de um ano) estou desenvolvendo em PHP em um projeto grande e antigo. Para garantir a qualidade do projeto, usamos autotestes na estrutura PHPUnit. Infelizmente, aconteceu que a maioria dos nossos autotestes são funcionais. Recentemente, percebemos que, se continuarmos a usar os autotestes da mesma maneira, em breve o tempo gasto na solução de problemas para não serem passados ​​para o CI se tornará mais do que o tempo gasto escrevendo código útil (na verdade não, mas cresce e não é agradável).
Para uma solução sistemática para esse problema, escolhemos uma abordagem que envolve escrever muitos testes de unidade e um nĂşmero mĂnimo de testes funcionais. TambĂ©m decidimos que, como parte das alterações necessárias no cĂłdigo existente, de acordo com a regra do escoteiro, atualize os testes existentes. Por um tempo - durante todo esse tempo, vimos novos recursos - tudo estava bem conosco. Recentemente, porĂ©m, uma tarefa foi executada para corrigir um bug no cĂłdigo antigo. Comecei a escrever testes de unidade e percebi que o antigo legado do mal acordava. Ficou claro que este Ă© o caminho para lugar nenhum:
- Eu escrevi alguns casos de teste por várias horas;
- Percebi que, durante esse perĂodo, escrevi um cĂłdigo muito, muito repetitivo;
- realmente nĂŁo fez nenhum trabalho Ăştil;
- no caso de uma alteração no DI, você precisará gastar muito tempo na adaptação inútil do código de teste.
, . — ,
— , — .
<?php declare(strict_types=1);
namespace Company\Bundle\Tests\Unit\Service;
use PHPUnit_Framework_MockObject_MockObject;
class TestedServiceTest extends Intelligent_PHPUnit_Framework_TestCase
{
public function test_getData_DataDescripion_ResultDescription(): void
{
$this
->diConstParam
->set("value")
;
$this
->dependencyRepository
->expects($this->once())
->method('findData')
->with(10, 10)
->will($this->returnValue([]))
;
$clazz = $this->getTestedClass();
$res = $clazz->getData();
}
}
. , -. , , - .
, PHPUnit 3.x. , 2014(!) , , , .
, — , , . , — (, , 20) -, , , unit- , .
, , « » :
- setUp.
- tearDown. , ,
- -.
- . , . — . . - , . …
Considere repetir fragmentos de cĂłdigo.
Mock Generation
Fragmento de cĂłdigo duplicado:$this->service = $this
->getMockBuilder(Service::class)
->disableOriginalConstructor()
->getMock()
;
O PHP tem um bom candidato para ocultar esse trabalho monótono monótono - uma função mágica:
__pegue
Mas ainda precisamos transmitir o tipo que estamos molhando. E entĂŁo uma ferramenta adequada foi encontrada - phpDoc:
@property Type $ service
No nosso caso, especialmente considerando as capacidades dos IDEs modernos, foi mais conveniente configurá-lo no seguinte formato:@property \ FQCN \ Service | \ PHPUnit_Framework_MockObject_MockObject $ service
Dentro da função __get da classe abstrata Intellegence_PHPUnit_Framework_TestCase, ocorre a metaprogramação, que analisa o phpDoc e forma zombarias com base em suas bases, disponĂveis como $ this-> propertyName na classe de teste. Atenção, todo o cĂłdigo fornecido no artigo Ă© um pouco pseudo-cĂłdigo, a versĂŁo completa está no repositĂłrio:
abstract class Intelligent_PHPUnit_Framework_TestCase extends PHPUnit_Framework_TestCase {
public function __get(string $name)
{
$property = $this->getPropertyBag()->get($name);
if ($property === false) {
throw new Exception("Invalid property name: ${name}");
}
return $property;
}
private function getPropertyBag(): PropertyBag
{
if ($this->propertyBag === null) {
$this->propertyBag = (new DocCommentParser())
->parse(
get_class($this),
function (string $className): PHPUnit_Framework_MockObject_MockObject {
return $this->createDefaultObjectMock($className);
}
);
}
return $this->propertyBag;
}
}
, phpDoc . :
class DocCommentParser
{
public function parse(
string $className,
callable $mockCreator
): PropertyBag {
$r = new ReflectionClass($className);
$docComment = $r->getDocComment();
if ($docComment === false) {
return new PropertyBag([]);
}
return $this->parseDocString($docComment, $mockCreator);
}
private function parseDocString(
string $docComment,
callable $mockCreator
): PropertyBag {
$map = [];
$constructorParams = [];
preg_match_all('/@property\s*(?<mock>(\S*)\|(\S+)\s*\$(\S+))/', $docComment, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (array_key_exists('mock', $match) && !empty($match['mock'])) {
if ($this->isMockObject($match[2])) {
$map[$match[4]] = $mockCreator($match[3]);
continue;
}
if ($this->isMockObject($match[3])) {
$map[$match[4]] = $mockCreator($match[2]);
continue;
}
}
}
return new PropertyBag($map);
}
}
? , — FQCN phpDoc property . — , .
-class ServiceTest extends PHPUnit_Framework_TestCase
{
private $repository;
protected function setUp()
{
parent::setUp();
$this
->repository = $this->getMockBuilder(DependencyRepository::class)
->disableOriginalConstructor()
->getMock()
;
}
protected function tearDown()
{
$this->repository = null;
parent::tearDown();
}
public function test_test()
{
}
}
class ServiceTest extends Intelligent_PHPUnit_Framework_TestCase
{
public function test_test()
{
}
}
3-4-5 ( ) — . , , , 7 — . , 20 — -.
. ! -, , .
:
public function test_case()
{
$this->clazz = $this->createTestClass(
$dependency1,
$dependency2,
$dependency3
);
}
, . php __call, phpDoc method.
, , ?! , property! , . , property — . — , .
, :
class ServiceTest
{
public function test_case()
{
$clazz = $this->getTestedClass();
}
}
__call:
abstract class Intelligent_PHPUnit_Framework_TestCase extends PHPUnit_Framework_TestCase
{
private const GET_TESTED_CLASS_METHOD_NAME = 'getTestedClass';
public function __call(string $method, array $params)
{
if ($method !== self::GET_TESTED_CLASS_METHOD_NAME) {
throw new Exception("Invalid method name: ${method}");
}
if (!array_key_exists(self::GET_TESTED_CLASS_METHOD_NAME, $this->getMethodsMap())) {
throw new Exception('Method ' . self::GET_TESTED_CLASS_METHOD_NAME . ' not annotated');
}
$params = $this->getPropertyBag()->getConstructorParams();
$paramValues = [];
foreach ($params as $param) {
$property = $this->__get($param);
$paramValues[] = $property;
}
$reflection = new ReflectionClass($this->getMethodsMap()[self::GET_TESTED_CLASS_METHOD_NAME]);
return $reflection->newInstanceArgs($paramValues);
}
}
? property:
class DocCommentParser
{
public function parse(
string $className,
callable $mockCreator
): PropertyBag {
$r = new ReflectionClass($className);
$docComment = $r->getDocComment();
if ($docComment === false) {
return new PropertyBag([], []);
}
return $this->parseDocString($docComment, $mockCreator);
}
private function parseDocString(
string $docComment,
callable $mockCreator
): PropertyBag {
$map = [];
$constructorParams = [];
preg_match_all('/@property\s*(?<mock>(\S*)\|(\S+)\s*\$(\S+))/', $docComment, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (array_key_exists('mock', $match) && !empty($match['mock'])) {
if ($this->isMockObject($match[2])) {
$map[$match[4]] = $mockCreator($match[3]);
$constructorParams[] = $match[4];
continue;
}
if ($this->isMockObject($match[3])) {
$map[$match[4]] = $mockCreator($match[2]);
$constructorParams[] = $match[4];
continue;
}
}
}
return new PropertyBag($map, $constructorParams);
}
}
. , . , DI - , , , — ,
-class ServiceTest extends PHPUnit_Framework_TestCase
{
private $repository;
protected function setUp()
{
parent::setUp();
$this
->repository = $this->getMockBuilder(DependencyRepository::class)
->disableOriginalConstructor()
->getMock()
;
}
protected function tearDown()
{
$this->repository = null;
parent::tearDown();
}
public function test_test()
{
$this->clazz = $this->createTestClass(repository);
}
private function createTestClass() {
return new TestedService($repository)
}
}
— . .
ConstDependencyInjectionParameter. , .