PHPUnit + Laravel单元测试常用技能(2)
断言成功结果:

3. 对异常进行测试
使用expectExceptionCode()对错误码进行检测,不建议对错误信息文案进行检测。例如检测设备被锁后是否抛出3026错误码。
示例代码:
<?php
namespace Tests\Unit;
use App\Services\UserSecurityService;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class UserSecurityServiceTest extends TestCase
{
public static $userId = 4;
/**
* 设备锁检测
* @throws \App\Exceptions\UserException
*/
public function testDeviceCheckLock()
{
$this->expectExceptionCode(3026);
Cache::put('device-login-error-account-', '1,2,3,4,5', 300);
UserSecurityService::$request = null;
UserSecurityService::$udid = null;
UserSecurityService::deviceCheck(self::$userId);
}
}
断言成功结果:

4. 测试私有属性和私有方法使用反射机制
如果只测试私有方法可使用ReflectionMethod()反射方法,使用setAccessible(true)设置方法可访问,并使用invokeArgs()或invoke()调用方法(invokeArgs将参数作为数组传递)。例如检测IP是否在白名单中。
示例代码:
被检测代码:
namespace App\Facades\Services;
/**
* Class WebDefender
*/
class WebDefenderService extends BaseService
{
//ip白名单
private $ipWhiteList = [
'10.*',
'172.18.*',
'127.0.0.1'
];
/**
* ip是否在白名单中
*
* @param string $ip
*
* @return bool
*/
private function checkIPWhiteList($ip)
{
if (!$this->ipWhiteList || !is_array($this->ipWhiteList)) {
return false;
}
foreach ($this->ipWhiteList as $item) {
if (preg_match("/{$item}/", $ip)) {
return true;
}
}
return false;
}
}
检测方法:
<?php
namespace Tests\Unit;
use App\Facades\Services\WebDefenderService;
use Tests\TestCase;
class WebDefenderTest extends TestCase
{
/**
* 测试IP白名单
* @dataProvider additionProviderIp
*
* @param $ip
* @param $result
*
* @throws \ReflectionException
*/
public function testIPWhite($ip, $result)
{
$checkIPWhiteList = new \ReflectionMethod(WebDefenderService::class, 'checkIPWhiteList');
$checkIPWhiteList->setAccessible(true);
$this->assertEquals($result, $checkIPWhiteList->invokeArgs(new WebDefenderService(), [$ip]));
}
public function additionProviderIp()
{
return [
'10 ip' => ['10.1.1.7', true],
'172 ip' => ['172.18.2.5', true],
'127 ip' => ['127.0.0.1', true],
'192 ip' => ['192.168.0.1', false]
];
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
