在模型laravel中编写特征单元测试



我已经编写了一个特性,用于将一些闭包模型事件自动添加到使用该特性的模型中。这是我的代码:

trait WatchCardListChange
{
public static function booted()
{
static::watchCardListChange();
}
protected static function watchCardListChange()
{
$modelClass = get_called_class();
$classParts = explode('\', $modelClass);
$className = end($classParts);
$method = 'addEventsTo' . $className . 'Model';
forward_static_call([$modelClass, $method]);
}
private static function addEventsToAcCardModel()
{
static::created(function ($model) {
CardListChanged::dispatch($model);
});
static::updated(function ($model) {
CardListChanged::dispatch($model);
});
static::deleted(function ($model) {
CardListChanged::dispatch($model);
});
}
}

我已经搜索了使用getMockForTrait为这个测试编写单元测试,这是我的代码:

public function test_trait()
{
// First approach
$mock = $this->partialMock(AcCard::class, function (MockInterface $mock) {
$mock->shouldAllowMockingProtectedMethods()->shouldReceive('booted')->once();
});
app()->instance(AcCard::class, $mock);
$model = new AcCard();
// Second approach
$trait = $this->getMockForTrait(WatchCardListChange::class, [], '', true, true, true, ['watchCardListChange']);
$trait->expects(self::exactly(1))->method('watchCardListChange');
// Test
$model = AcCard::factory()->create();
}

但这两种方法似乎都不起作用。

我想知道测试这种特质的最佳实践是什么?有人能帮忙吗?

尝试使用mocking框架Mockery;该技术正在重载一个类/方法:

use Mockery as m;
...
m::mock('overload:FullNamespaceToWatchCardListChange', function ($mock) {
$mock->shouldReceive('watchCardListChange')
->once()
->andReturn(whatever);
})->shouldIgnoreMissing();

这将继续创建一个模拟到位;现在,您可以随心所欲地测试静态调用;您甚至可以在函数本身内部模拟一些东西,当它被调用时,mock对象将返回的值将被替换到位。

最新更新