cornermonkey/phpunit-conditional-assertions

PHPUnit 测试用例扩展,允许执行条件断言。

0.1.0 2023-11-09 23:14 UTC

This package is auto-updated.

Last update: 2024-09-10 01:21:07 UTC


README

此库增加了对 PHPUnit 的任何现有断言进行条件调用的功能。此库的灵感来自 Pest 的条件期望以及希望在 PHPUnit 中实现类似功能。

作者和版权

Tim Lawson tim@lawson.fyi
此库采用 MIT 许可证

安装

$ composer require --dev cornermonkey/phpunit-conditional-assertions

兼容性

此包与 PHP 8.0 及更高版本以及 PHPUnit 8.0 及更高版本兼容。

用法

只需在您的测试用例中使用 trait CornerMonkey\ConditionalAssertions\ConditionalAssertionTrait。此 trait 为您的测试用例添加了 whenunless 方法。

示例

<?php
use CornerMonkey\ConditionalAssertion\ConditionalAssertionTrait;
use PHPUnit\Framework\TestCase;

class MyTestCase extends TestCase
{
  use ConditionalAssertionTrait;

  public function testConditionIsValid()
  {
    
    $this->when(true)->assertThat(true, true);
    $this->when(false)->assertThat(true, true);    // This assertion will not be called
    $this->unless(true)->assertThat(true, true);   // This assertion will not be called
    $this->unless(false)->assertThat(true, true);
    
  }
}

您还可以将回调函数传递给 whenunless 方法。当条件为真时,将调用提供的回调。

<?php
use CornerMonkey\ConditionalAssertion\ConditionalAssertionTrait;
use PHPUnit\Framework\TestCase;

class MyTestCase extends TestCase
{
  use ConditionalAssertionTrait;
   
  public function dataProvider()
  {
    return [
      [true],
      [false]
    ];
  }
  /** 
    * @dataProvider dataProvider
    */
  public function testIfExceptionShouldBeThrown($shouldThrow)
  {
    $this->when($shouldThrow, function(TestCase $testCase, $value) {
      $testCase->expectException(Exception::class);
    });
    
    if ($shouldThrow) {
      throw new Exception();
    }
  }
}