jchook/phpunit-assert-throws

PHPUnit 的异常断言

v1.0.3 2019-04-13 22:17 UTC

This package is auto-updated.

Last update: 2024-09-22 07:51:55 UTC


README

基于 lambda 的行业标准异常测试断言,适用于 PHPUnit。

安装

使用 composer 轻松安装

composer require --dev jchook/phpunit-assert-throws

或者,也可以复制这个 tiny gist并将其添加到您的项目中。无需署名。真正的艺术家是窃贼。

理由

为了使基于 lambda 的异常测试语法能够应用于 PHPUnit

  • 每个测试抛出多个错误
  • 捕获错误后进行审查和测试
  • 复制粘贴使用示例
  • 使用标准的 assert* 语法
  • 测试不仅仅是 messagecodeclass
  • 使用 assertNotThrows 编写简单的 happy-path 测试

示例

仅为了说明语法的精髓

<?php

// Within your test case...
$x = new MyTestedObject();
$this->assertThrows(
  MyException::class,
  fn() => $x->doSomethingBad()
);

高级示例

下面的类演示了更高级的功能。

<?php

declare(strict_types=1);

// PHPUnit
use PHPUnit\Framework\TestCase;

// This library
use Jchook\AssertThrows\AssertThrows;

// Your classes
use MyNamespace\MyException;
use MyNamespace\MyObject;

final class MyTest extends TestCase
{
	use AssertThrows; // <--- adds the assertThrows method

	public function testMyObject()
	{
		$obj = new MyObject();

		// Ensure that a function throws a specific exception
		$this->assertThrows(MyException::class, function() use ($obj) {
			$obj->doSomethingBad();
		});

		// Test custom aspects of a custom extension class
		$this->assertThrows(MyException::class,
			function() use ($obj) {
				$obj->doSomethingBad();
			},
			function($exception) {
				$this->assertEquals('Expected value', $exception->getCustomThing());
				$this->assertEquals(123, $exception->getCode());
			}
		);

		// Test that a specific method does *NOT* throw
		$this->assertNotThrows(MyException::class, function() use ($obj) {
			$obj->doSomethingGood();
		});
	}
}

?>

注意

是的,assertNotThrows() 在语法上感觉有些...奇怪。然而,它符合 PHPUnit 的命名约定,例如 assertNotContains()。此外,PHPUnit 团队建议我们可能不需要这个反向断言 [链接]

许可证

MIT