5
2

More than 3 years have passed since last update.

Mockery\Exception\BadMethodCallException: Received 自分の関数(), but no expectations were specified

Posted at

表題のエラーにハマったので共有します。

背景

Repositoryにアクセスが必要なメソッドを書いたあと、全体テストをしていました。
おかしなことに、自分のテストではなく他人の書いたMockを使ったテストが落ちました。
ちなみに自分のコードではMockを使っていませんし、完全に独立したメソッドを書いていたはずなのに。。。

CorrectLoadFactorCommand.php
public function __construct(ShopRepository $shop_repository)
    {
        parent::__construct();
        $this->shop_repository = $shop_repository;
        $this->occurrence_day = today()->day;
        $this->target_measuring_day = today()->subDay(2)->day;
        $this->target_day_end_of_month = today()->subDay(2)->endOfMonth()->day;
        $this->fetched_cn_cds = $this->fetchLoadFactorCnCds($this->occurrence_day, $this->target_measuring_day, $this->target_day_end_of_month);
    }

    /**
     * 今日から2日前の検査日の店舗一覧を取得する。
     * @param int $occurrence_day
     * @param int $target_measuring_day
     * @param int $target_day_end_of_month
     * @return string
     */
    private function fetchLoadFactorCnCds(int $occurrence_day, int $target_measuring_day, int $target_day_end_of_month): string
    {
        // 省略

        return
            $this->shop_repository
                ->fetchLoadFactorCnCds($target_day_list)
                ->implode(',');
ShopRepository.php
    /**
     *
     * @param array $target_date_list
     * @return Collection
     */
    public function fetchLoadFactorCnCds(array $target_date_list): Collection;
EloquentShopRepository.php
public function fetchLoadFactorCnCds(array $target_date_list): Collection
    {
        return $this->shop
            ->with('eSettings')
            ->join('e_settings', 'stores.cn_cd', 'e_settings.cn_cd')
            ->where('status_id', '=', 1)
            ->where('e_contract_id', '=', 70)
            ->whereIn('measuring_date', $target_date_list)
            ->pluck('stores.cn_cd');
    }

試行1(返り値や引数の型)

もしかしたらno expectations were specifiedと言われるので、返り値指定や
引数指定がされてないのかと思ったがハズレ。
nullが返ってくる様なこともなく、期待通りCollectionでした。

試行2(config:clear)

https://qiita.com/tkek321/items/26d420215b92a1d98e95
こちらにconfig:clearで動くとあったので、やってみましたが関係ありませんでした。

試行3($this->fetched_cn_cdsをローカル変数化)

コンストラクタで読んでいるのを、ローカル変数に変更して呼び出す様変更しました。

CorrectLoadFactorCommand.php
public function handle()
    {
        $logger = new BatchLogger(array_slice(explode('\\', get_class($this)), -1)[0]);
        $fetched_cn_cds = $this->fetchLoadFactorCnCds($this->occurrence_day, $this->target_measuring_day, $this->target_day_end_of_month);
    // 省略
    }

テストが通る様になりました!
おそらく他人の書いたMock呼び出し部分で、DBを参照をコンストラクタで
呼び出されると不都合なことになるのでしょう。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2