首页 > 解决方案 > 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() 内部注册了观察者

标签: laravellaravel-5

解决方案


推荐阅读