laravel - Laravel 5.4:观察者事件不适用于 PHPUnit
问题描述
我正在尝试为我的 User 类测试模型观察者,并且我遇到了与许多其他程序员相同的问题。
使用 PHPUnit 时,updated/updated/... 事件不会触发。尝试使用修补程序。
所以这就是问题所在:我尝试了这个解决方案。不幸的是没有成功。
这是我的测试类:
class UserObserverTest extends TestCase {
use DatabaseTransactions;
public function setUp()
{
parent::setUp();
$this->user = factory("App\User")->create();
$this->plan = new UserSettings();
$this->difficulty1 = factory("App\Difficulty")->create();
$this->difficulty2 = factory("App\Difficulty")->create();
$this->plan->getExercisePlan()->appendAppExercise(factory("App\Exercise")->create(), false, $this->difficulty1, Constants::VORWAERTS);
$this->plan->getExercisePlan()->appendAppExercise(factory("App\Exercise")->create(), false, $this->difficulty2, Constants::VORWAERTS);
$this->user->settings = $this->plan->toJson();
$this->user->save();
$this->user = $this->user->fresh();
}
public function test_Difficulty2HasUsedCounter0AfterDeletingFromPlan()
{
$this->assertEquals(1, $this->difficulty2->fresh()->used);
$plan = new UserSettings($this->user->settings);
$exercises = $plan->getExercisePlan()->getExercisesArray();
array_pull($exercises, 1);
$this->user->settings = $plan->toJson();
$this->user->save();
$this->assertEquals(0, $this->difficulty2->fresh()->used);
}
}
用户观察者:
class UserObserver
{
/**
* Listen to the User updating event
* @param User $user
*/
public function updating(User $user)
{
$settings = new UserSettings($user->settings);
foreach($settings->getExercisePlan()->getExercisesArray() as $exercise)
{
$difficulty = Difficulty::find($exercise->getDifficultyId());
$difficulty->used--;
$difficulty->save();
}
}
/**
* Listen to the user updated event
* @param User $user
*/
public function updated(User $user)
{
$settings = new UserSettings($user->settings);
foreach($settings->getExercisePlan()->getExercisesArray() as $exercise)
{
$difficulty = Difficulty::find($exercise->getDifficultyId());
$difficulty->used++;
$difficulty->save();
}
}
/**
* Listen to the User deleting event.
*
* @param User $user
* @return void
*/
public function deleting(User $user)
{
$settings = new UserSettings($user->settings);
foreach($settings->getExercisePlan()->getExercisesArray() as $exercise)
{
$difficulty = Difficulty::find($exercise->getDifficultyId());
$difficulty->used--;
$difficulty->save();
}
}
}
User::observe(UserObserver::class);
我使用AppServiceProvider 的 boot() 内部注册了观察者
解决方案
推荐阅读
- php - angular api联系形式安全
- python - Pyomo (PySP) 正在将“\”更改为“/”
- python - 如何以行块的形式检查进程的持续时间?
- networkx - NetworkX 2.X minimum_node_cut
- python - 在 QLineEdit 上模拟 returnPressed 信号
- spring-boot - 一个模块可以读取另一个模块的bean吗?
- scala - 如何使用 circe 将对象的 JSON 表示“展平”,即从案例类到其字符串表示?
- c# - TextArea 在 Razor Page 帖子上失去价值
- java - Java内存泄漏与重复对象创建
- java - 确定在 Hive 中创建 UDF 的语言