我正在尝试为我的User类测试模型Observer,并且遇到与许多其他程序员相同的问题。
使用PHPUnit时不会触发update / updated / ...事件。与修补匠一起尝试。
这就是问题所在:我尝试了solution。不幸的是没有成功。
这是我的TestClass:
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);
}
}
UserObserver:
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();
}
}
}
我在AppServiceProvider的boot()中使用User::observe(UserObserver::class);
注册了观察者