您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit对方法上桩抛出异常-throwException
发布时间:2021-09-22 17:39:16编辑:雪饮阅读()
上篇了解了上桩方法的返回值列表,上桩方法除了返回值列表外还可以让上桩的方法抛出一个异常。用throwException来实现抛出一个异常。
DatabaseTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class DatabaseTest extends TestCase
{
public function testThrowExceptionStub(): void
{
// 为 SomeClass 类创建桩件。
$stub = $this->createStub(Database::class);
// 配置桩件。
$stub->method('doSomething')
->will($this->throwException(new Exception));
//断言一个异常
$this->expectException(Exception::class);
// $stub->doSomething() 抛出异常
$stub->doSomething();
}
}
use PHPUnit\Framework\TestCase;
final class DatabaseTest extends TestCase
{
public function testThrowExceptionStub(): void
{
// 为 SomeClass 类创建桩件。
$stub = $this->createStub(Database::class);
// 配置桩件。
$stub->method('doSomething')
->will($this->throwException(new Exception));
//断言一个异常
$this->expectException(Exception::class);
// $stub->doSomething() 抛出异常
$stub->doSomething();
}
}
C:\Users\Administrator\PhpstormProjects\untitled\organizing>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\organizing\tests\DatabaseTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 00:00.004, Memory: 20.00 MB
OK (1 test, 1 assertion)
关键字词:phpunit,throwException