我需要帮助,因为我不是PHPUNIT的专家。
我觉得当我在我的测试类中实例化我的Validator两次时,PHPUNIT会忽略第二个实例......
这是我的代码: ```的PHP
<?php
namespace Tests\Validation;
use PHPUnit\Framework\TestCase;
use Validation\Validator;
class ValidatorTest extends TestCase
{
public function testIsNotValid()
{
$_POST['input_test'] = '1';
$validator = new Validator();
$validator->rules([
'input_test' => [
'alpha '=> true, // "$_POST['input_test']" must be alpha
],
]);
// "isValid()" must return "false", and PHPUNIT returns "false"
$this->assertFalse($validator->isValid());
// "count($validator->getErrors())" Must return "1", and PHPUNIT returns "1"
$this->assertEquals(1, count($validator->getErrors()));
}
public function testIsValid()
{
$_POST['input_test'] = 'aaa';
$validator = new Validator();
$validator->rules([
'input_test' => [
'alpha' => true, // "$_POST['input_test']" must be alpha
],
]);
// "isValid()" must return "true", but PHPUNIT returns "false"
$this->assertTrue($validator->isValid());
// "count($validator->getErrors())" must return "0", but PHPUNIT returns "1"
$this->assertEquals(0, count($validator->getErrors()));
}
}
``` 所以我的测试“testIsValid()”无法正常工作。另一方面,如果我删除测试“testIsNotValid()”,测试“testIsValid()”开始工作......
有人有想法吗?
非常感谢。
答案 0 :(得分:0)
谢谢,这是我的验证器类:
<?php
class Validator implements ValidatorInterface
{
/**
* Name du input
*
* @var string
*/
private $input;
/**
* Valeur des rules qu'on passe à un input
*
* @var mixed
*/
private $value;
/**
* POST ou GET - Sera à POST par defaut
*
* @var mixed
*/
private $requestMethod;
/**
* Contiendra les éventuels erreurs
*
* @var array
*/
private $errors = [];
/**
* Validator constructor.
*
* @param null $requestMethod
*/
public function __construct()
{
$this->requestMethod = $_POST;
}
/**
* Vérification des données soumises
*
* @param array $array
*/
public function rules(array $array)
{
foreach ($array as $input => $rules) {
$this->input = $input;
if (is_array($rules)) {
foreach ($rules as $rule => $value) {
if ($rule != 'label') {
if ($rule == 'required' || $rule == 'file' || isset($this->requestMethod[$this->input])) {
$this->value = $value;
$this->callRule($rule);
}
}
}
}
}
}
/**
* Appeler la règle de validation
*
* @param string $rule
*/
protected function callRule(string $rule)
{
$methodVerify = 'verify'.Str::convertSnakeCaseToCamelCase($rule);
if (method_exists($this, $methodVerify)) {
$this->$methodVerify();
}
}
/**
* Vérifier que valeur entrée dans le champ est bien alphabétique
*/
private function verifyAlpha()
{
if ($this->value === true && !preg_match(self::REGEX_ALPHA, $this->requestMethod[$this->input])) {
$this->errors[$this->input] = $this->pushError('alpha');
}
}
/**
* @return bool - True si formulaire soumis est valide, false si pas valide
*/
public function isValid(): bool
{
return count($this->errors) === 0;
}
}
谢谢