2017-05-30 3 views
1

職場のコマンドクラスから呼び出されるサービスクラスにコンソール出力ロガーを追加するためのベストプラクティスは何ですか?Laravel Artisanコンソール出力をサービス中、ユニットテスト可能

コード例:

<?php 
class Import extends Command 
{ 
    public function handle() 
    { 
      /** @var \Services\ServiceImport $service */ 
      $service = resolve($this->resolvers[$db]) 
       ->setCommand($this); 

      # Console output 
      $this->info(sprintf('Starting import for "%s"', $service::SERVICE_NAME)); 
      $imported = $service->import($this->argument('file')); 

      $this->info(sprintf('Total rows imported: %d', $imported)); 
     } 
    } 
} 

/** Different file, service from container */ 

class ServiceImport extends Service 
{ 
    protected $cmd; 

    public function import($file) 
    { 
     # Need this console output 
     $this->cmd->info(sprintf('Importing file "%s"', $file)); 
     // [...] More stuff goes on..this illustrates my point 
    } 

    public function setCommand(Command $cmd) 
    { 
     $this->cmd = $cmd; 
     return $this; 
    } 
} 

$cmdが設定されていない...そして、私はCommandはこれを取得モックする方法を考え出していなかったので、これは、動作しますが、ユニットテストServiceImportしようとすると失敗しますいずれか、働いています。これをどのように達成するのですか?

私は何かが欠けていると確信しています。私はどのようにサービスを利用していますか?処理中に冗長なログを実行し続ける唯一の人物にはなりません。

Laravel 5.4、artisanコマンドを使用します。

Log::をコンソールに書き込むとき(素晴らしいSymfonyの色で)、私は特に使いたくありません。

答えて

1

ログ出力を作成したいのであれば、nullのチェックでこれを解決できます。あなたのサービスで

はちょうどそうのような関数パラメータとコマンドの依存関係を注入:これはあなたのサービスコードに影響を与えるべきではないとして、あなたのテストでは

public function import($file, Command $cmd = null) 
{ 
    # Need this console output 
    if($cmd != null) { 
     $this->cmd->info(sprintf('Importing file "%s"', $file)); 
    } 
    // [...] More stuff goes on..this illustrates my point 
} 

は、あなたが簡単に$cmd引数を省略することができます。

あなたは過度に、出力のこの種を使用するなどの機能を持つ形質または基本クラスを作成する場合:

public function info(string $message, Command $cmd = null) 
{ 
    if($cmd != null){ 
     $cmd->info($message); 
    } else { 
     //perhaps log message otherwise in test environment 
     // or when service is used outside of artisan commands 
    } 
} 

そして、あなたははい、あなたのサービスではどこでも

$this->info(sprintf('Importing file "%s"', $file), $cmd); 
+0

をこれを使用することができます。あなたが正しい。そして私が発見した解決策に近い。私が行ったことは、AbstractCommandクラスを介して$ cmdを注入し、そのためにrun()を上書きします。 Partyline(https://statamic.com/blog/partyline)をアプローチとして使用しましたが、Monologスタックに注入できる完全なPSR Loggerを作成しました。完璧に動作します。詳細情報:https://redd.it/6j42h5 – guice

関連する問題