codeception/domain-assert

为 PHPUnit 和 Codeception 定制的断言

1.0.1 2020-03-27 09:50 UTC

This package is auto-updated.

Last update: 2024-08-27 20:01:01 UTC


README

由 Symfony Expression Language 驱动的 PHPUnitCodeception 断言库。

简介

这个小型库帮助您在测试中创建特定领域的断言

代替

$this->assertTrue($user->isValid(), 'user is valid');

使用

$this->assertUserIsValid($user);

为什么?

看看第一个例子中测试是如何失败的

user is valid
Failed asserting that false is true.

看看第二个例子中测试是如何失败的

Failed asserting that `user.isValid()`.
[user]: User Object &000000005689696e000000004066036e (
    'role' => 'guest'
)

哪个对你更有意义?在第二个例子中,你不仅得到了断言背后的业务逻辑,还得到了传递给它的值。这就是为什么如果你的项目中包含业务逻辑,那么“domain-assert”是你的选择。

如何使用

安装此软件包

composer require codeception/domain-assert --dev

创建一个包含自定义断言的 trait我们建议使用 traits,因为你可以跨不同的测试用例重用它们。

use Codeception\DomainRule;

trait CustomAssertion
{
    public function assertValidUser(User $user)
    {
        $this->assertThat(
            ['user' => $user], 
            new DomainRule('user and user.isValid()')
        );
    }
}

在这个例子中,我们检查 $user 是否存在并且 $user->isValid() 返回 true;

就是这样!现在将此 trait 注入到 TestCases 并使用它。

class UserTest extends \PHPUnit\Framework\TestCase
{
    use CustomAssertion;
}

定义业务规则

此库使用 Expression Language 来定义断言的业务规则。

让我们定义一个规则来检查库存中是否有足够的产品

stock and product.getStock() == stock and product.getAmount() > amount

这里有 3 个元素:productstockamount,这是我们需要的项目的数量。让我们根据这个规则创建一个断言

public function assertEnoughProductsInStock(Stock stock, Product product, amount)
{
    $this->assertThat([
            'product' => $product,
            'stock' => $stock, 
            'amount' => $amount
        ], 
        new DomainRule('stock and product.getStock() == stock and product.getAmount() > amount')
    );
}

现在它可以在你的测试中使用

$product = new Product('iPhone');
$stock->addProduct($product);
$stock->addProduct($product);
$stock->addProduct($product);
$this->assertEnoughProductsInStock($stock, $product, 2);

高级概念

  • 除了 $this->assertThat,你还可以调用此方法的静态版本:PHPUnit\Framework\Assert::assertThat
  • Codeception\DomainRule 扩展了 PHPUnit\Framework\Constraint
  • Codeception\DomainRule 使用了 Symfony\Component\ExpressionLanguage\ExpressionLanguage
  • 可以通过调用 $domainRule->getLanguage() 来扩展表达式语言
  • assertThat 可以接受第一个参数作为标量值。在这种情况下,它将在表达式内部被视为 expected
public function assertIsGreaterThanMinimal()
{
    $this->assertThat(
        $minimalPrice,
        new DomainRule('expected > 1000')
    );    
}

许可证

开源软件,根据 MIT 许可证授权。© Codeception PHP 测试框架