カテゴリー
Laravel

UnitTestでconfig()が使えないンゴ…

LaravelのEloquentのUnitTestを書いていて、Eloquentの中にconfig()を利用するものがあったんやけども、そこがエラーになった。

 Target class [config] does not exist.

  at vendor/laravel/framework/src/Illuminate/Container/Container.php:807
    803| 
    804|         try {
    805|             $reflector = new ReflectionClass($concrete);
    806|         } catch (ReflectionException $e) {
  > 807|             throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
    808|         }
    809| 
    810|         // If the type is not instantiable, the developer is attempting to resolve
    811|         // an abstract type such as an Interface or Abstract Class and there is

コンテナにconfigが登録されてないでってことらしいで。ということなので、UnitTest実行時にコンテナに登録してみた。

app()->bind('config', function () {
                return new class {
                    public function get(...$args)
                    {
                        return 'なんてすごいんだ……(恍惚)';
                    }
                };
            });

とりあえずテキストが返ればよかったので、こんな感じで解決できた。

やっぱりEloquentの中でconfig()直接使うなってことなんやなと。横着せずに、ちゃんと外から渡して疎結合にしろってはっきりわかんだね。

カテゴリー
Laravel

UnitTestでEloquentの日付情報を操作するとエラーになるンゴ…

LaravelのEloquentをUnitTestするときに、日付の属性をセットしようとすると下記のエラーになった。

 Call to a member function connection() on null

  at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1342
    1338|      * @return \Illuminate\Database\Connection
    1339|      */
    1340|     public static function resolveConnection($connection = null)
    1341|     {
  > 1342|         return static::$resolver->connection($connection);
    1343|     }

データベースのコネクションを探しているようや。これは、日付の属性をセットするときは、データベースへのアクセスが必要になるためらしいんやが…。

    /**
     * Get the format for database stored dates.
     *
     * @return string
     */
    public function getDateFormat()
    {
        return $this->dateFormat ?: $this->getConnection()->getQueryGrammar()->getDateFormat();
    }

なるほど、日付のフォーマットをデータベースタイプから参照してくれる機能のおかげみたいや。

    /**
     * Set the date format used by the model.
     *
     * @param  string  $format
     * @return $this
     */
    public function setDateFormat($format)
    {
        $this->dateFormat = $format;

        return $this;
    }

フォーマットは直接指定できるようなので、Eloquentで指定しておけばええみたいや。

これで、データベースのコネクションエラーにならずにEloquentの日付属性を利用するようなUnitTestも動くようになったで。