Skip to content

Instantly share code, notes, and snippets.

@baudev
Created March 8, 2019 21:57
Show Gist options
  • Save baudev/1983635797aa4c920c51260a1ece58db to your computer and use it in GitHub Desktop.
Save baudev/1983635797aa4c920c51260a1ece58db to your computer and use it in GitHub Desktop.
PHPUnits custom assertions using Symfony Validator
<?php
/**
* Created by Baudev
* http://github.com/baudev
* Date: 08/03/2019
*/
namespace App\Tests\Helper; // according to your project
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Decorated TestCase class.
*
* @package App\Tests\Helper
* @author Baudev
* @since 1.0
* @link https://phpunit.readthedocs.io/en/8.0/extending-phpunit.html
*/
abstract class CustomTestCase extends TestCase {
/**
* Adds the assertion using Symfony Validator.
*
* @param $condition
* @param string $message
* @see ValidatorInterface
*/
public static function assertSymfonyValidate($condition, $message = ''){
self::assertThat($condition, self::isSymfonyValidate(), $message);
}
/**
* Returns the evaluation class.
*
* @return IsSymfonyValidate
* @see IsSymfonyValidate::matches()
*/
public static function isSymfonyValidate() {
return new IsSymfonyValidate;
}
}
<?php
/**
* Created by Baudev
* http://github.com/baudev
* Date: 08/03/2019
*/
namespace App\Tests\Helper; // according to your project
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\Validator\Validation;
/**
* Evaluation class using the Symfony Validator.
*
* @package App\Tests\Helper
* @author Baudev
* @since 1.0
* @link https://symfony.com/doc/current/validation.html
*/
class IsSymfonyValidate extends Constraint
{
/**
* @var \Symfony\Component\Validator\Validator\RecursiveValidator|\Symfony\Component\Validator\Validator\ValidatorInterface
*/
private $validator;
/**
* IsSymfonyValidate constructor.
*/
public function __construct()
{
parent::__construct();
$this->validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator();
}
/**
* Evaluates if the object $other is validated by the Symfony Normalizer.
*
* @param mixed $other
* @return bool
*/
protected function matches($other)
{
return $this->validator->validate($other)->count() === 0;
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString()
{
return 'is validated';
}
}
@baudev
Copy link
Author

baudev commented Mar 8, 2019

Tested with Symfony 4.2, PHPUnits 8.0, PHP 7.2.15.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment